app / src /ClipForge.Infrastructure /Services /VoiceGenerationService.cs
Vanderson da Silva Quintino
Initial deploy: ClipForge video generator
8fb6238
Raw History Blame Contribute Delete
3.1 kB
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<VoiceAsset> _voiceRepository;
private readonly IFfmpegService _ffmpeg;
private readonly StorageSettings _storage;
private readonly ILogger<VoiceGenerationService> _logger;
public VoiceGenerationService(
EdgeTtsService edgeTts,
IVideoScriptRepository scriptRepository,
IRepository<VoiceAsset> voiceRepository,
IFfmpegService ffmpeg,
IOptions<StorageSettings> storage,
ILogger<VoiceGenerationService> logger)
{
_edgeTts = edgeTts;
_scriptRepository = scriptRepository;
_voiceRepository = voiceRepository;
_ffmpeg = ffmpeg;
_storage = storage.Value;
_logger = logger;
}
public async Task<VoiceAsset> 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;
}
}