利用百度语音API进行语音识别。

由于项目需要,这几天都在试图利用百度语音API进行语音识别。但是识别到的都是“啊,哦”什么的,我就哭了。

这里我只是分享一下这个过程,错误感觉出现在Post语音数据那一块,可能是转换问题吧。

API请求地址::http://vop.baidu.com/server_api

语音上传模式:显示发送:将语音数据直接放在 HTTP-BODY 中

其他参数:cuid:用户id,token:密钥 ,lan:语言等
要了解更多请查看官方文档:http://developer.baidu.com/wiki/index.php?title=docs/cplat/media/voice

实现的步骤:1、录音,将文件存储起来     2、获取token     3、Post数据并请求获取返回值

1、录音

String fileName = "test.wav";

private MediaCapture _mediaCaptureManager;

private StorageFile _recordStorageFile;

private async void record_Click(object sender, RoutedEventArgs e)//点击后开始录音

{

  try

  {

    //在临时文件夹Temp中创建文件,存在的话就替换掉

    _recordStorageFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

     //关键就是这俩句

    MediaEncodingProfile recordProfile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto);//录音-WAV格式

     await _mediaCaptureManager.StartRecordToStorageFileAsync(recordProfile, this._recordStorageFile);//将录音保存到创建的文件中

  }

  catch (Exception ex)

  {

    Debug.WriteLine(ex.Message.ToString());

  }

}

private async void stop_Click(object sender, RoutedEventArgs e)

{

  await _mediaCaptureManager.StopRecordAsync();//停止录音

}

2、获取token

private void GetToken()

        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id="

                + "申请的API_KEY" + "&client_secret=" + “申请的SECRET_KEY”);

            request.BeginGetResponse(ResponseTokenCall, request);

        }



        private void ResponseTokenCall(IAsyncResult result)

        {

            try

            {

                HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState;

                WebResponse webResponse = httpWebRequest.EndGetResponse(result);

                using (Stream stream = webResponse.GetResponseStream())

                using (StreamReader reader = new StreamReader(stream))

                {

                    string content = reader.ReadToEnd();

                    string ssss = content.Replace("\"", "").Replace("{", "").Replace("}", "").Replace("\n", "");

                    string[] indexs = ssss.Split(',');

                    foreach (string index in indexs)

                    {

                        string[] _indexs = index.Split(':');

                        if (_indexs[0] == "access_token")

                            token = _indexs[1];//获取到的token

                    }

                }

            }



            catch (Exception ex)

            {

                Debug.WriteLine("获取Token失败");

            }

        }

3、发送请求

private async void Post()

        {

            string serverURL = "http://vop.baidu.com/server_api?";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverURL + "lan=zh&cuid=" + cuid + "&token=" + token);//cuid = Guid.NewGuid().ToString();  官方推荐使用 mac 地址/手机 IMEI 等类似参数,只要唯一就好 

            request.ContinueTimeout = 10000;//超时

            request.Method = "POST";//Post请求



            //post data

            request.BeginGetRequestStream(ResponseStreamCallbackPost, request);//Post数据

        }



        private async void ResponseStreamCallbackPost(IAsyncResult result)

        {

          StorageFile storageFile = await ApplicationData.Current.TemporaryFolder.GetFileAsync(fileName);//取出临时文件夹中保存的音频文件



            IBuffer buffer = await FileIO.ReadBufferAsync(storageFile);//读取文件至Ibuffer           byte[] voice = WindowsRuntimeBufferExtensions.ToArray(buffer, 0, (int)buffer.Length);//将Ibuffer转换为byte[]

            
      HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState; httpWebRequest.ContentType = "audio/wav;rate=8000";//参数设置 using (Stream writeStream = httpWebRequest.EndGetRequestStream(result)) { writeStream.Write(voice, 0, voice.Length);//写入 } httpWebRequest.BeginGetResponse(ResponseCall, httpWebRequest);//发送请求 } private void ResponseCall(IAsyncResult result) { try { HttpWebRequest httpWebRequest = (HttpWebRequest)result.AsyncState; WebResponse webResponse = httpWebRequest.EndGetResponse(result); using (Stream stream = webResponse.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string content = reader.ReadToEnd();//返回的是utf-8编码 string a = Regex.Unescape(content);//进行转换 } } catch (Exception ex) { Debug.WriteLine("识别失败"); } }

token获取了一次,是说30天后会过期。
在处理过程中,遇到了一个问题。我让GetToken()和Post()先后进行处理,但是却发现token是在Post之后才得到的,这就导致了请求的URL里面不含token了。

所以还是要先获取了token之后再进行。

另外(HttpWebRequest)request无法给Content-length属性进行赋值。

 

你可能感兴趣的:(api)