前不久寫了個工具型微信小程序(Find周邊),里面用到了語音識別技術。現將實現細節(jié)整理如下: 接口預覽通過閱讀了解科大訊飛接口文檔、小程序接口開發(fā)文檔以及對后端ThinkPhp框架的學習,我整理了如下開發(fā)步驟:
音頻錄制接口
wx.startRecord()和wx.stopRecord()接口也可以滿足需求,但從1.6.0 版本開始不再被微信團隊維護。建議使用能力更強的 wx.getRecorderManager 接口。該接口獲取到的音頻格式為silk。 silk是webm格式通過base64編碼后的結果,我們解碼后需要將webm轉換成pcm、wav
相對wx.startRecord()接口,該接口提供的能力更為強大(詳情),可以暫停錄音也可以繼續(xù)錄音,根據自己需求設置編碼碼率,錄音通道數,采樣率。最讓人開心的是可以指定音頻格式,有效值 aac/mp3。不好的是wx.getRecorderManager()在1.6.0才開始被支持。當然如果你要兼容低端微信用戶需要使用wx.startRecord()做兼容處理。
// wxjs: const recorderManager = wx.getRecorderManager() recorderManager.onStart(() => { //開始錄制的回調方法 }) //錄音停止函數 recorderManager.onStop((res) => { const { tempFilePath } = res; //上傳錄制的音頻 wx.uploadFile({ url: app.d.hostUrl + '/Api/Index/wxupload', //僅為示例,非真實的接口地址 filePath: tempFilePath, name: 'viceo', success: function (res) { console.log(res); } }) }) Page({ //按下按鈕--錄音 startHandel: function () { console.log("開始") recorderManager.start({ duration: 10000 }) }, //松開按鈕 endHandle: function () { console.log("結束") //觸發(fā)錄音停止 recorderManager.stop() } }) //wxml: <view bindtouchstart='startHandel' bindtouchend='endHandle' class="tapview"> <text>{{text}}</text> </view> 音頻轉換我這邊后端使用php的開源框架thinkphp,當然node、java、python等后端語言都可以,你根據自己的喜好和能力來。想做好音頻轉碼我們就要借助音視頻轉碼工具ffmpeg、avconv,它們都依賴于gcc。安裝過程大家可以自行百度,或者關注我后面的文章。 <?php namespace Api\Controller; use Think\Controller; class IndexController extends Controller { //音頻上傳編解碼 public function wxupload(){ $upload_res=$_FILES['viceo']; $tempfile = file_get_contents($upload_res['tmp_name']); $wavname = substr($upload_res['name'],0,strripos($upload_res['name'],".")).".wav"; $arr = explode(",", $tempfile); $path = 'Aduio/'.$upload_res['name']; if ($arr && !empty(strstr($tempfile,'base64'))){ //微信模擬器錄制的音頻文件可以直接存儲返回 file_put_contents($path, base64_decode($arr[1])); $data['path'] = $path; apiResponse("success","轉碼成功!",$data); }else{ //手機錄音文件 $path = 'Aduio/'.$upload_res['name']; $newpath = 'Aduio/'.$wavname; file_put_contents($path, $tempfile); chmod($path, 0777); $exec1 = "avconv -i /home/wwwroot/mapxcx.kanziqiang.top/$path -vn -f wav /home/wwwroot/mapxcx.kanziqiang.top/$newpath"; exec($exec1,$info,$status); chmod($newpath, 0777); if ( !empty($tempfile) && $status == 0 ) { $data['path'] = $newpath; apiResponse("success","轉碼成功!",$data); } } apiResponse("error","發(fā)生未知錯誤!"); } //json數據返回方法封裝 function apiResponse($flag = 'error', $message = '',$data = array()){ $result = array('flag'=>$flag,'message'=>$message,'data'=>$data); print json_encode($result);exit; } } 調用識別接口當我們把文件準備好之后,接下來我們就可以將base64編碼之后的音頻文件通過api接口請求傳輸過去。期間我們要注意嚴格按照文檔中所說的規(guī)范傳輸,否則將造成不可知的結果。 <?php namespace Api\Controller; use Think\Controller; class IndexController extends Controller { public function _initialize(){ } //封裝數據請求方法 public function httpsRequest($url,$data = null,$xparam){ $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_HEADER, 0); $Appid = "";//開放平臺的appid $Appkey = "";//開放平臺的Appkey $curtime = time(); $CheckSum = md5($Appkey.$curtime.$xparam.$data); $headers = array( 'X-Appid:'.$Appid, 'X-CurTime:'.$curtime, 'X-CheckSum:'.$CheckSum, 'X-Param:'.$xparam, 'Content-Type:'.'application/x-www-form-urlencoded; charset=utf-8' ); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); if (!empty($data)){ curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; } //請求接口數據處理 public function getVoice($path){ $d = base64_encode($path); $url = "https://api.xfyun.cn/v1/aiui/v1/voice_semantic"; $xparam = base64_encode( json_encode(array('scene' => 'main','userid'=>'user_0001',"auf"=>"16k","aue"=>"raw","spx_fsize"=>"60" ))); $data = "data=".$d; $res = $this->httpsRequest($url,$data,$xparam); if(!empty($res) && $res['code'] == 00000){ apiResponse("success","識別成功!",$res); }else{ apiResponse("error","識別失??!"); } } //數據返回封裝 function apiResponse($flag = 'error', $message = '',$data = array()){ $result = array('flag'=>$flag,'message'=>$message,'data'=>$data); print json_encode($result);exit; } } |