Lex chatbot C# client with voice

风格不统一 提交于 2019-11-28 05:22:22

问题


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);
                }

回答1:


You have to set the Position of your MemoryStream to 0 before you pass it to the post request.

memoryStream.Position = 0;


来源:https://stackoverflow.com/questions/45026213/lex-chatbot-c-sharp-client-with-voice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!