I have the chatbot client running with text but would now like to change it to voice but I am unsure of how to get the stream from the mic for post. For recording audio I am using NAudio but when sending the memory stream I get an error stating
System.IO.IOException: Cannot close stream until all bytes are written.
Here is my code:
private void recordAudio()
{
if (memoryStream == null)
memoryStream = new MemoryStream();
sourceStream = new NAudio.Wave.WaveIn();
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(16000, 1);
waveIn = new NAudio.Wave.WaveInProvider(sourceStream);
waveWriter = new WaveFileWriter(new IgnoreDisposeStream(memoryStream), waveIn.WaveFormat);
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable);
buff = new BufferedWaveProvider(waveIn.WaveFormat);
sourceStream.StartRecording();
mytimer.Enabled = true;
}
private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
buff.AddSamples(e.Buffer, 0, e.BytesRecorded);
Console.WriteLine("test");
}
void mytimer_Tick(object sender, EventArgs e)
{
if (sourceStream != null)
{
sourceStream.StopRecording();
waveWriter.Flush();
var amazonLexClient = new AmazonLexClient(Amazon.RegionEndpoint.USEast1);
var amazonPostRequest = new Amazon.Lex.Model.PostContentRequest();
var amazonPostResponse = new Amazon.Lex.Model.PostContentResponse();
amazonPostRequest.BotAlias = "voiceBot";
amazonPostRequest.BotName = "voiceBot";
amazonPostRequest.ContentType = "audio/l16; rate=16000; channels=1";
amazonPostRequest.UserId = "user";
amazonPostRequest.InputStream = memoryStream;
amazonPostRequest.UserId = "test";
try
{
amazonPostResponse = amazonLexClient.PostContent(amazonPostRequest);
Console.WriteLine("Got a response");
}
catch (Exception w)
{
Console.WriteLine("{0} Exception caught.", e);
Console.WriteLine(w.Message);
}
You have to set the Position of your MemoryStream to 0 before you pass it to the post request.