I am developing a chatbot client. I managed to run it with text input and is now properly working. Now I want to add a voice input feature but currently having issues. I am currently using NAudio to record my input but I am having this error
Inner Exception 1: AmazonServiceException: A WebException with status RequestCanceled was thrown.
Inner Exception 2: WebException: The request was aborted: The request was canceled.
Inner Exception 3: IOException: Cannot close stream until all bytes are written.
Here is what I have done so far:
Boolean voiceEnabled = false;
private void voiceButton_Click(object sender, EventArgs e)
{
if (voiceEnabled)
{
voiceButton.BackgroundImage = Properties.Resources.mic_d;
voiceEnabled = false;
StopRecord();
}
else
{
voiceButton.BackgroundImage = Properties.Resources.mic_e;
voiceEnabled = true;
StartRecord();
}
}
WaveIn waveIn;
WaveFileWriter waveWriter;
Stream memoryStream;
private void waveIn_DataAvailable(object sender, WaveInEventArgs e)
{
if (waveWriter == null) return;
waveWriter.Write(e.Buffer, 0, e.BytesRecorded);
waveWriter.Flush();
}
private void StartRecord()
{
if (memoryStream == null)
memoryStream = new MemoryStream();
waveIn = new WaveIn();
waveIn.DeviceNumber = 0;
waveIn.WaveFormat = new WaveFormat(16000, 1);
waveIn.DataAvailable += new EventHandler<WaveInEventArgs>(waveIn_DataAvailable);
waveWriter = new WaveFileWriter(new IgnoreDisposeStream(memoryStream), waveIn.WaveFormat);
waveIn.StartRecording();
}
private void StopRecord()
{
if (waveIn != null)
{
waveIn.StopRecording();
waveIn.Dispose();
waveIn = null;
}
if (waveWriter != null)
{
waveWriter.Dispose();
waveWriter = null;
}
SendReq(memoryStream);
}
private void SendReq(Stream stream)
{
PostContentRequest postContentRequest = new PostContentRequest();
postContentRequest.BotAlias = "Test";
postContentRequest.BotName = "TestBot";
postContentRequest.ContentType = "audio/l16; rate=16000; channels=1";
postContentRequest.InputStream = stream;
postContentRequest.UserId = "user";
Task<PostContentResponse> task = amazonLexClient.PostContentAsync(postContentRequest);
task.Wait();
PostContentResponse postContentResponse = task.Result;
Console.WriteLine(postContentResponse.Message);
//this just plays the audio
PlayAudio(postContentResponse.AudioStream);
}