我正在开发一个聊天机器人客户端。我设法通过文本输入运行它,现在可以正常工作。现在我想添加一个语音输入功能,但目前有问题。我目前正在使用 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);
}