Created
October 16, 2019 08:11
-
-
Save notjulian/5a2bee248a21a860cc4b7ef7432b1055 to your computer and use it in GitHub Desktop.
Generate wav file with Amazon Polly and .NET C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using Amazon.Polly; //nuget AWSSDK.Core AWSSDK.Polly | |
using Amazon.Polly.Model; | |
using NAudio.Wave; //nuget NAudio | |
public class SpeechGenerator | |
{ | |
public string awsAccessKey = ""; | |
public string awsAccessSecret = ""; | |
public async void GenerateVoiceWavFromText(string textMessage, string path, string fileName) | |
{ | |
if (string.IsNullOrEmpty(textMessage)) | |
{ | |
throw new Exception("textMessage can't be empty"); | |
} | |
if (string.IsNullOrEmpty(path)) | |
{ | |
throw new Exception("path can't be empty"); | |
} | |
if (string.IsNullOrEmpty(fileName)) | |
{ | |
throw new Exception("fileName can't be empty"); | |
} | |
if (!Directory.Exists(path)) | |
{ | |
Directory.CreateDirectory(path); | |
} | |
string outputFileName = Path.Combine(path, fileName); | |
var config = new AmazonPollyConfig(); | |
var client = new AmazonPollyClient(this.awsAccessKey, this.awsAccessSecret, config); | |
var synthesizeSpeechRequest = new SynthesizeSpeechRequest() | |
{ | |
OutputFormat = OutputFormat.Pcm, | |
VoiceId = VoiceId.Brian, | |
Text = textMessage, | |
}; | |
using (var outputStream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write)) | |
{ | |
var synthesizeSpeechResponse = await client.SynthesizeSpeechAsync(synthesizeSpeechRequest); | |
byte[] buffer = new byte[2 * 1024]; | |
int readBytes; | |
var inputStream = synthesizeSpeechResponse.AudioStream; | |
while ((readBytes = inputStream.Read(buffer, 0, 2 * 1024)) > 0) | |
{ | |
outputStream.Write(buffer, 0, readBytes); | |
} | |
outputStream.Flush(); | |
outputStream.Close(); | |
} | |
using (var readPcmStream = File.OpenRead(outputFileName)) | |
{ | |
using (var rawWaveStream = new RawSourceWaveStream(readPcmStream, new WaveFormat(16000, 1))) | |
{ | |
var outpath = outputFileName + ".wav"; | |
WaveFileWriter.CreateWaveFile(outpath, rawWaveStream); | |
rawWaveStream.Close(); | |
} | |
readPcmStream.Close(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment