using ClipForge.Core.Entities; using ClipForge.Core.Interfaces; using ClipForge.Core.Interfaces.Services; using ClipForge.Infrastructure.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace ClipForge.Infrastructure.Services; public class VoiceGenerationService : IVoiceGenerationService { private readonly EdgeTtsService _edgeTts; private readonly IVideoScriptRepository _scriptRepository; private readonly IRepository _voiceRepository; private readonly IFfmpegService _ffmpeg; private readonly StorageSettings _storage; private readonly ILogger _logger; public VoiceGenerationService( EdgeTtsService edgeTts, IVideoScriptRepository scriptRepository, IRepository voiceRepository, IFfmpegService ffmpeg, IOptions storage, ILogger logger) { _edgeTts = edgeTts; _scriptRepository = scriptRepository; _voiceRepository = voiceRepository; _ffmpeg = ffmpeg; _storage = storage.Value; _logger = logger; } public async Task GenerateVoiceAsync(Guid scriptId, string voiceId = "pt-BR-FranciscaNeural", CancellationToken ct = default) { var script = await _scriptRepository.GetByIdAsync(scriptId, ct) ?? throw new InvalidOperationException($"Script {scriptId} not found"); _logger.LogInformation("Generating voice for script {ScriptId} with Edge TTS voice {VoiceId}", scriptId, voiceId); // Map simple voice names to Edge TTS voices var edgeVoice = voiceId switch { "alloy" or "female" or "francisca" => EdgeTtsService.Voices.FranciscaPtBr, "male" or "antonio" => EdgeTtsService.Voices.AntonioNeural, "young" or "thalita" => EdgeTtsService.Voices.ThalitaNeural, _ when voiceId.Contains("Neural") => voiceId, // Already a full Edge voice name _ => EdgeTtsService.Voices.FranciscaPtBr }; var audioBytes = await _edgeTts.SynthesizeSpeechAsync(script.ScriptText, edgeVoice, ct); // Save audio file var audioDir = Path.Combine(_storage.BasePath, _storage.AudioFolder); Directory.CreateDirectory(audioDir); var fileName = $"{scriptId}_{edgeVoice}.mp3"; var filePath = Path.Combine(audioDir, fileName); await File.WriteAllBytesAsync(filePath, audioBytes, ct); // Get duration var duration = await _ffmpeg.GetMediaDurationAsync(filePath, ct); var voiceAsset = new VoiceAsset { VideoScriptId = scriptId, FilePath = filePath, VoiceProvider = "edge-tts", VoiceId = edgeVoice, DurationSeconds = duration, FileSizeBytes = audioBytes.Length }; await _voiceRepository.AddAsync(voiceAsset, ct); _logger.LogInformation("Voice generated: {FilePath}, duration: {Duration}s", filePath, duration); return voiceAsset; } }