1 Answer
- Newest
- Most votes
- Most comments
0
using System;
using Amazon;
using Amazon.Polly;
using Amazon.Polly.Model;
using System.IO;
using System.Threading.Tasks;
namespace PollyExample
{
class Program
{
static async Task Main(string[] args)
{
string textToSynthesize = "Hello, welcome to AWS Polly!";
string voiceIdString = "Joanna"; // Replace with your desired VoiceId
string outputFilePath = "speech.mp3";
// Specify the AWS region that supports the Neural engine
RegionEndpoint region = RegionEndpoint.USEast1; // Example: us-east-1
// Initialize the Polly client
var pollyClient = new AmazonPollyClient(region);
// Attempt to use the Neural engine
var synthesizeSpeechRequest = new SynthesizeSpeechRequest()
{
OutputFormat = OutputFormat.Mp3,
VoiceId = VoiceIdStringToVoiceId(voiceIdString),
Text = textToSynthesize,
Engine = Engine.Neural
};
try
{
var synthesizeSpeechResponse = await pollyClient.SynthesizeSpeechAsync(synthesizeSpeechRequest);
using (var fileStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
{
synthesizeSpeechResponse.AudioStream.CopyTo(fileStream);
}
Console.WriteLine($"Speech synthesized and saved to {outputFilePath} using Neural engine.");
}
catch (AmazonPollyException ex)
{
// Handle specific Polly exceptions
if (ex.Message.Contains("The selected engine is not supported in this region"))
{
Console.WriteLine("Neural engine is not supported in this region. Falling back to standard engine.");
// Retry with standard engine
var standardEngineRequest = new SynthesizeSpeechRequest()
{
OutputFormat = OutputFormat.Mp3,
VoiceId = VoiceIdStringToVoiceId(voiceIdString),
Text = textToSynthesize,
Engine = Engine.Standard
};
try
{
var standardResponse = await pollyClient.SynthesizeSpeechAsync(standardEngineRequest);
using (var fileStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
{
standardResponse.AudioStream.CopyTo(fileStream);
}
Console.WriteLine($"Speech synthesized and saved to {outputFilePath} using Standard engine.");
}
catch (AmazonPollyException innerEx)
{
Console.WriteLine($"Error synthesizing speech with Standard engine: {innerEx.Message}");
}
}
else
{
// Handle other Polly exceptions
Console.WriteLine($"Polly error: {ex.Message}");
}
}
catch (Exception ex)
{
// Handle non-Polly exceptions
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
/// <summary>
/// Converts a string VoiceId to the Polly VoiceId enum.
/// </summary>
/// <param name="voiceIdString">The VoiceId as a string.</param>
/// <returns>The corresponding VoiceId enum value.</returns>
static VoiceId VoiceIdStringToVoiceId(string voiceIdString)
{
if (Enum.TryParse<VoiceId>(voiceIdString, out var voiceId))
{
return voiceId;
}
else
{
throw new ArgumentException($"Invalid VoiceId: {voiceIdString}");
}
}
}
}
answered 2 years ago
Relevant content
asked 2 years ago
asked 2 years ago
- AWS OFFICIALUpdated 4 years ago
