Unity 百度语音识别
前言本篇文章演示在unity引擎中接入百度语音识别API(适用于Windows平台,其它平台的后续更新)
需要的准备(1)百度智能云账号(2)百度智能云产品服务-语音技术-领取免费资源-创建应用(3)创建Unity工程-UI面板制作(4)调用百度语音识别
具体步骤(1)注册好百度智能云账号之后就可以开始制作一个语音识别的程序。(2)领取免费资源以及创建应用
可调用的接口功能都在此页面中创建应用(3)创建Unity工程,制作UI面板这一步操作很简单,只需要一个Text文本框和两个按钮就OK了(4)调用百度语音现在就可以开始写脚本去调用百度语音识别了,可以分为两步:①AccessToken的获取获取的详解可以查看鉴权认证机制编写获取AccessToken的代码:
//////获取accessToken请求令牌//////IEnumerator_GetAccessToken(){varuri=string.Format("https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id={0}&client_secret={1}",api_key,secret_Key);UnityWebRequestunityWebRequest=UnityWebRequest.Get(uri);yieldreturnunityWebRequest.SendWebRequest();if(unityWebRequest.isDone){Matchmatch=Regex.Match(unityWebRequest.downloadHandler.text,@"access_token.:.(.*?).,");if(match.Success){Debug.Log("Token已经匹配");accessToken=match.Groups[1].ToString();}else{Debug.Log("验证错误,获取AccessToken失败!!!");}}}②进行语音识别,获取返回数据并显示
//////请求语音识别//////IEnumeratorRequestASR(){if(string.IsNullOrEmpty(accessToken)){yieldreturn_GetAccessToken();}resulrStr=string.Empty;//处理当前录音数据为PCM16float[]samples=newfloat[recordFrequency*10*saveAudioClip.channels];saveAudioClip.GetData(samples,0);varsamplesShort=newshort[samples.Length];for(varindex=0;indexresulrStr=unityWebRequest.downloadHandler.text;if(Regex.IsMatch(resulrStr,@"err_msg.:.success")){Matchmatch=Regex.Match(resulrStr,"result.:..(.*?)..]");if(match.Success){resulrStr=match.Groups[1].ToString();}}else{resulrStr="识别结果为空";}resultText.text=resulrStr;}}全篇代码如下:
usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Text.RegularExpressions;usingUnityEngine;usingUnityEngine.UI;usingUnityEngine.Networking;usingSystem;publicclassSpeechScript:MonoBehaviour{//自行填写自己的百度语音识别相关keypublicstringapi_key;publicstringsecret_Key;stringaccessToken=string.Empty;boolishaveMic=false;//检测是否连接麦克风stringcurrentDeviceName=string.Empty;//当前录音设备名称intrecordFrequency=8000;//录音频率intrecordMaxTime=20;//最大录音时长AudioClipsaveAudioClip;//存储当前录音的片段AudioSourcesource;stringresulrStr;//存储识别结果TextresultText;//显示识别结果ButtonstartBtn;//开始识别按钮ButtonendBtn;//结束识别按钮voidStart(){//saveAudioClip=this.transform.GetComponent();source=this.transform.GetComponent();resultText=GameObject.Find("Canvas/panel/speech").GetComponent();startBtn=GameObject.Find("Canvas/Start").GetComponent();endBtn=GameObject.Find("Canvas/End").GetComponent();StartCoroutine(_GetAccessToken());//获取accessTokenstartBtn.onClick.AddListener(StartRecord);endBtn.onClick.AddListener(EndRecord);}//////开始录音///voidStartRecord(){saveAudioClip=Microphone.Start(currentDeviceName,false,recordMaxTime,recordFrequency);}//////结束录音///voidEndRecord(){Microphone.End(currentDeviceName);source.PlayOneShot(saveAudioClip);StartCoroutine(RequestASR());//请求语音识别}//////请求语音识别//////IEnumeratorRequestASR(){if(string.IsNullOrEmpty(accessToken)){yieldreturn_GetAccessToken();}resulrStr=string.Empty;//处理当前录音数据为PCM16float[]samples=newfloat[recordFrequency*10*saveAudioClip.channels];saveAudioClip.GetData(samples,0);varsamplesShort=newshort[samples.Length];for(varindex=0;indexresulrStr=unityWebRequest.downloadHandler.text;if(Regex.IsMatch(resulrStr,@"err_msg.:.success")){Matchmatch=Regex.Match(resulrStr,"result.:..(.*?)..]");if(match.Success){resulrStr=match.Groups[1].ToString();}}else{resulrStr="识别结果为空";}resultText.text=resulrStr;}}//////获取accessToken请求令牌//////IEnumerator_GetAccessToken(){varuri=string.Format("https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id={0}&client_secret={1}",api_key,secret_Key);UnityWebRequestunityWebRequest=UnityWebRequest.Get(uri);yieldreturnunityWebRequest.SendWebRequest();if(unityWebRequest.isDone){Matchmatch=Regex.Match(unityWebRequest.downloadHandler.text,@"access_token.:.(.*?).,");if(match.Success){Debug.Log("Token已经匹配");accessToken=match.Groups[1].ToString();}else{Debug.Log("验证错误,获取AccessToken失败!!!");}}}}演示效果: