Spaces:
Sleeping
Sleeping
File size: 3,102 Bytes
8fb6238 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | 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;
}
}
|