I have this class, which uses Text-to-speech service from Microsoft. I want to save the audio file of the speech, but i don't know how to not play the sound to user on web(using Blazor Server app).
using Microsoft.CognitiveServices.Speech;
public class TextToSpeechService : ITextToSpeechService
{
public async Task SpeakSsmlAndSaveToFile(string text, string filePath)
{
var speechConfig = SpeechConfig.FromSubscription("5c4d780b81cb40fca6bd555cc3148765", "westeurope");
speechConfig.SpeechSynthesisVoiceName = "sk-SK-LukasNeural";
string ssml = $"<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='en-US'>" +
$"<voice name='sk-SK-LukasNeural'>{text}</voice></speak>";
filePath = "wwwroot\\Audio\\DictationRecordings\\" + filePath;
using (var speechSynthesizer = new SpeechSynthesizer(speechConfig))
{
var result = await speechSynthesizer.SpeakSsmlAsync(ssml);
if (result.Reason == ResultReason.SynthesizingAudioCompleted)
{
Console.WriteLine($"Speech synthesized for SSML: [{ssml}], and the result is being written to file: {filePath}");
using (var audioDataStream = AudioDataStream.FromResult(result))
{
await audioDataStream.SaveToWaveFileAsync(filePath);
}
}
else if (result.Reason == ResultReason.Canceled)
{
var cancellation = SpeechSynthesisCancellationDetails.FromResult(result);
Console.WriteLine($"CANCELED: Reason={cancellation.Reason}");
if (cancellation.Reason == CancellationReason.Error)
{
Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}");
Console.WriteLine($"CANCELED: ErrorDetails= [{cancellation.ErrorDetails}]");
Console.WriteLine($"CANCELED: Did you set the speech resource key and region values?");
}
}
}
}
}
I tried the following sample Blazor server app code to convert text to speech without playing it in the browser.
Code :
TextToSpeechServivce.cs :
index.raror :
Output:
The code ran successfully, as shown below:
Browser output:
I received the following page in my browser: I wrote a line and clicked the "Convert" button. This action converted the text to speech and saved the speech audio to an output.wav file without playing it in the browser, as shown below.
The audio is saved to the output.wav file below.