Thursday, January 5, 2017

Text to speech conversion using Amazon Polly and .Net

Nuget Package

AWSSDK.Polly

Code

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.Polly;
using Amazon.Polly.Model;
using Amazon;
using System.IO;

namespace PollyTest
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
AmazonPollyClient client = new AmazonPollyClient(RegionEndpoint.USWest2);

DescribeVoicesRequest voiceRequest = new DescribeVoicesRequest();
DescribeVoicesResponse voiceResponse = client.DescribeVoices(voiceRequest);
var voicesList = voiceResponse.Voices;
SynthesizeSpeechRequest synthesizeRequest = new SynthesizeSpeechRequest()
{
Text = "Well, that was easy!",
VoiceId = voicesList[0].Id,
OutputFormat = OutputFormat.Mp3
};
var synthesizeResponse = client.SynthesizeSpeech(synthesizeRequest);

byte[] mp3Bytes = ReadToEnd(synthesizeResponse.AudioStream);
File.WriteAllBytes(@"C:\temp\easy.mp3", mp3Bytes);
}

public static byte[] ReadToEnd(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
}
}
}