Files
astrocore/Astrocore.Api/Controllers/TextToSpeechController.cs
2025-06-16 19:25:43 -04:00

68 lines
2.4 KiB
C#

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Net.Http;
using System.Text;
using System.Text.Json;
namespace Astrocore.Api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TextToSpeechController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
public TextToSpeechController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public async Task<IActionResult> Index(string message)
{
var client = _httpClientFactory.CreateClient();
var body = $"msg={Uri.EscapeDataString(message)}&lang=Geraint&source=ttsmp3";
var request = new HttpRequestMessage(HttpMethod.Post, "https://ttsmp3.com/makemp3_new.php")
{
Content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded")
};
var response = await client.SendAsync(request);
var json = await response.Content.ReadAsStringAsync();
using var doc = JsonDocument.Parse(json);
var mp3File = doc.RootElement.GetProperty("URL").GetString();
var mp3Bytes = await client.GetByteArrayAsync(mp3File);
var tempDir = Path.GetTempPath();
var mp3Path = Path.Combine(tempDir, "tts.mp3");
var dfpwmPath = Path.Combine(tempDir, "tts.dfpwm");
await System.IO.File.WriteAllBytesAsync(mp3Path, mp3Bytes);
var process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "ffmpeg",
Arguments = $"-i \"{mp3Path}\" -ac 1 -c:a dfpwm -ar 48k \"{dfpwmPath}\"",
RedirectStandardError = true,
UseShellExecute = false
}
};
process.Start();
string errorOutput = await process.StandardError.ReadToEndAsync();
process.WaitForExit();
if (!System.IO.File.Exists(dfpwmPath))
{
return StatusCode(500, $"FFmpeg failed: {errorOutput}");
}
var dfpwmBytes = await System.IO.File.ReadAllBytesAsync(dfpwmPath);
return File(dfpwmBytes, "application/octet-stream", "tts.dfpwm");
}
}
}