C# AWS.Polly Speech Synthesizer
Nov 9, 2017

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

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();
    }
}
csharp Related
Comments