我正在开发一个聊天机器人客户端。我设法用文本输入运行它,现在正常工作。现在我想添加一个语音输入功能,但目前有问题。我目前正在使用NAudio来录制我的输入,但我有这个错误
内部异常1:AmazonServiceException:抛出状态为RequestCanceled的WebException。
内部例外2: WebException:请求已中止:请求已取消。
内部例外3: IOException:在写入所有字节之前无法关闭流。
这是我到目前为止所做的:
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);
}