app / src /ClipForge.Infrastructure /Services /EdgeTtsService.cs
Vanderson da Silva Quintino
Initial deploy: ClipForge video generator
8fb6238
Raw History Blame Contribute Delete
7.72 kB
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Text;
using Microsoft.Extensions.Logging;
namespace ClipForge.Infrastructure.Services;
/// <summary>
/// Edge TTS implementation using Microsoft Edge's speech synthesis WebSocket API.
/// Free, no API key required, high quality voices in multiple languages.
/// Based on https://github.com/rany2/edge-tts
/// </summary>
public class EdgeTtsService
{
private const string TrustedClientToken = "6A5AA1D4EAFF4E9FB37E23D68491D6F4";
private const string ChromiumFullVersion = "143.0.3650.75";
private const string ChromiumMajor = "143";
private const long WinEpoch = 11644473600;
private const double SToNs = 1e9;
private static string WssUrl =>
$"wss://speech.platform.bing.com/consumer/speech/synthesize/readaloud/edge/v1?TrustedClientToken={TrustedClientToken}&Sec-MS-GEC={GenerateSecMsGec()}&Sec-MS-GEC-Version=1-{ChromiumFullVersion}";
private readonly ILogger<EdgeTtsService> _logger;
public static class Voices
{
public const string FranciscaPtBr = "pt-BR-FranciscaNeural";
public const string AntonioNeural = "pt-BR-AntonioNeural";
public const string ThalitaNeural = "pt-BR-ThalitaNeural";
}
public EdgeTtsService(ILogger<EdgeTtsService> logger)
{
_logger = logger;
}
public async Task<byte[]> SynthesizeSpeechAsync(string text, string voice = "pt-BR-FranciscaNeural", CancellationToken ct = default)
{
_logger.LogInformation("Generating TTS with Edge voice '{Voice}', text length: {Length}", voice, text.Length);
// Retry up to 3 times
for (int attempt = 1; attempt <= 3; attempt++)
{
try
{
var result = await TrySynthesizeAsync(text, voice, ct);
if (result.Length > 0)
return result;
}
catch (Exception ex) when (attempt < 3)
{
_logger.LogWarning(ex, "Edge TTS attempt {Attempt} failed, retrying...", attempt);
await Task.Delay(1000 * attempt, ct);
}
}
// Final attempt - let it throw
return await TrySynthesizeAsync(text, voice, ct);
}
private async Task<byte[]> TrySynthesizeAsync(string text, string voice, CancellationToken ct)
{
_logger.LogInformation("Generating TTS with Edge voice '{Voice}', text length: {Length}", voice, text.Length);
using var ws = new ClientWebSocket();
// Headers matching edge-tts Python library
ws.Options.SetRequestHeader("Pragma", "no-cache");
ws.Options.SetRequestHeader("Cache-Control", "no-cache");
ws.Options.SetRequestHeader("Origin", "chrome-extension://jdiccldimpdaibmpdkjnbmckianbfold");
ws.Options.SetRequestHeader("User-Agent",
$"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{ChromiumMajor}.0.0.0 Safari/537.36 Edg/{ChromiumMajor}.0.0.0");
ws.Options.SetRequestHeader("Accept-Encoding", "gzip, deflate, br, zstd");
ws.Options.SetRequestHeader("Accept-Language", "en-US,en;q=0.9");
// MUID cookie
var muid = GenerateMuid();
ws.Options.SetRequestHeader("Cookie", $"muid={muid};");
var url = WssUrl;
_logger.LogDebug("Connecting to Edge TTS WebSocket");
await ws.ConnectAsync(new Uri(url), ct);
var requestId = Guid.NewGuid().ToString("N");
// Send configuration
var configMessage =
$"X-Timestamp:{GetTimestamp()}\r\n" +
"Content-Type:application/json; charset=utf-8\r\n" +
"Path:speech.config\r\n\r\n" +
"{\"context\":{\"synthesis\":{\"audio\":{\"metadataoptions\":{\"sentenceBoundaryEnabled\":\"false\",\"wordBoundaryEnabled\":\"false\"},\"outputFormat\":\"audio-24khz-48kbitrate-mono-mp3\"}}}}";
await SendTextAsync(ws, configMessage, ct);
// Send SSML
var ssml = $"<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='pt-BR'>" +
$"<voice name='{voice}'><prosody pitch='+0Hz' rate='+0%' volume='+0%'>{EscapeXml(text)}</prosody></voice></speak>";
var ssmlMessage =
$"X-RequestId:{requestId}\r\n" +
"Content-Type:application/ssml+xml\r\n" +
$"X-Timestamp:{GetTimestamp()}\r\n" +
"Path:ssml\r\n\r\n" +
ssml;
await SendTextAsync(ws, ssmlMessage, ct);
// Receive audio data
var audioData = new List<byte>();
var buffer = new byte[32768];
while (ws.State == WebSocketState.Open)
{
var result = await ws.ReceiveAsync(buffer, ct);
if (result.MessageType == WebSocketMessageType.Close)
break;
if (result.MessageType == WebSocketMessageType.Binary)
{
// Binary messages: first 2 bytes are header length (big-endian)
if (result.Count > 2)
{
int headerLen = (buffer[0] << 8) | buffer[1];
int audioStart = 2 + headerLen;
if (audioStart < result.Count)
{
var audioChunk = new byte[result.Count - audioStart];
Array.Copy(buffer, audioStart, audioChunk, 0, audioChunk.Length);
audioData.AddRange(audioChunk);
}
}
}
else if (result.MessageType == WebSocketMessageType.Text)
{
var msg = Encoding.UTF8.GetString(buffer, 0, result.Count);
if (msg.Contains("Path:turn.end"))
break;
}
}
if (ws.State == WebSocketState.Open)
{
try { await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "done", ct); }
catch { /* ignore close errors */ }
}
_logger.LogInformation("Edge TTS generated {Bytes} bytes of audio", audioData.Count);
return audioData.ToArray();
}
/// <summary>
/// Generates the Sec-MS-GEC token value (SHA256 hash of rounded timestamp + token).
/// Matches the Python edge-tts DRM implementation.
/// </summary>
private static string GenerateSecMsGec()
{
// Get current Unix timestamp
var ticks = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
// Convert to Windows file time epoch
ticks += WinEpoch;
// Round down to nearest 5 minutes (300 seconds)
ticks -= ticks % 300;
// Convert to 100-nanosecond intervals (Windows file time format)
var nsValue = (long)(ticks * SToNs / 100);
// Hash: "{ticks}{TrustedClientToken}"
var strToHash = $"{nsValue}{TrustedClientToken}";
var hashBytes = SHA256.HashData(Encoding.ASCII.GetBytes(strToHash));
return Convert.ToHexString(hashBytes);
}
private static string GenerateMuid()
{
var bytes = new byte[16];
RandomNumberGenerator.Fill(bytes);
return Convert.ToHexString(bytes);
}
private static async Task SendTextAsync(ClientWebSocket ws, string message, CancellationToken ct)
{
var bytes = Encoding.UTF8.GetBytes(message);
await ws.SendAsync(bytes, WebSocketMessageType.Text, true, ct);
}
private static string GetTimestamp()
=> DateTime.UtcNow.ToString("ddd MMM dd yyyy HH:mm:ss") + " GMT+0000 (Coordinated Universal Time)";
private static string EscapeXml(string text)
=> text.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;").Replace("\"", "&quot;").Replace("'", "&apos;");
}