C# AWS.Polly Speech Synthesizer

Use NuGet to install the AWSSDK.Polly / NAudio packages.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using Amazon.Polly;
using Amazon.Polly.Model;
using NAudio.Wave;
AmazonPollyClient polly = new AmazonPollyClient(..., ..., Amazon.RegionEndpoint.USEast1);
var req = new SynthesizeSpeechRequest();
req.VoiceId = VoiceId.Emma;
req.TextType = TextType.Text;
req.Text = tts;
req.OutputFormat = OutputFormat.Pcm;
req.SampleRate = "16000";
var response = polly.SynthesizeSpeech(req);
using (var ms = new MemoryStream())
{
response.AudioStream.CopyTo(ms);
byte[] buf = ms.GetBuffer();
var source = new BufferedWaveProvider(new WaveFormat(16000, 16, 1));
source.ReadFully = false;
source.AddSamples(buf, 0, buf.Length);
using (WaveOutEvent waveOut = new WaveOutEvent())
{
waveOut.Init(source);
AutoResetEvent stopped = new AutoResetEvent(false);
waveOut.PlaybackStopped += (object sender, StoppedEventArgs e) => { stopped.Set(); };
waveOut.Play();
stopped.WaitOne();
}
}