64 lines
2.0 KiB
Plaintext
64 lines
2.0 KiB
Plaintext
@page "/text-to-speech"
|
|
@using System.Text.Json
|
|
@using System.Text
|
|
@inject HttpClient Http
|
|
@inject IJSRuntime JS
|
|
@inject IConfiguration _configuration
|
|
|
|
<h3>Text to Speech</h3>
|
|
|
|
<textarea @bind="InputText" rows="5" cols="60" placeholder="Enter text here..."></textarea>
|
|
<br />
|
|
<button @onclick="ConvertTextToSpeech">Convert to Speech</button>
|
|
|
|
<audio id="audioPlayer" controls style="display:none;"></audio>
|
|
|
|
@code {
|
|
private string InputText = string.Empty;
|
|
|
|
private string GetApiKey() =>
|
|
_configuration?.GetSection("ElevenLabsAPI")?.GetValue<string>("ApiKey") ?? string.Empty;
|
|
|
|
private async Task ConvertTextToSpeech()
|
|
{
|
|
if (string.IsNullOrWhiteSpace(InputText))
|
|
return;
|
|
|
|
var requestContent = new
|
|
{
|
|
text = InputText,
|
|
// model_id = "eleven_multilingual_v2",
|
|
model_id = "eleven_flash_v2_5",
|
|
voice_settings = new
|
|
{
|
|
stability = 0.5,
|
|
similarity_boost = 0.75
|
|
}
|
|
};
|
|
|
|
var requestJson = JsonSerializer.Serialize(requestContent);
|
|
var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://api.elevenlabs.io/v1/text-to-speech/yyPLNYHg3CvjlSdSOdLh/stream")
|
|
{
|
|
Content = new StringContent(requestJson, Encoding.UTF8, "application/json")
|
|
};
|
|
|
|
httpRequest.Headers.Add("xi-api-key", GetApiKey());
|
|
|
|
var response = await Http.SendAsync(httpRequest);
|
|
if (response.IsSuccessStatusCode)
|
|
{
|
|
var audioBytes = await response.Content.ReadAsByteArrayAsync();
|
|
var base64Audio = Convert.ToBase64String(audioBytes);
|
|
var audioDataUrl = $"data:audio/mpeg;base64,{base64Audio}";
|
|
|
|
await JS.InvokeVoidAsync("playAudio", audioDataUrl);
|
|
}
|
|
else
|
|
{
|
|
// Handle error response
|
|
var errorContent = await response.Content.ReadAsStringAsync();
|
|
Console.Error.WriteLine($"Error: {errorContent}");
|
|
}
|
|
}
|
|
}
|