网友真实露脸自拍10p,成人国产精品秘?久久久按摩,国产精品久久久久久无码不卡,成人免费区一区二区三区

小程序模板網

小程序實現語音識別到底要填多少坑?

發(fā)布時間:2018-05-05 14:53 所屬欄目:小程序開發(fā)教程

前不久寫了個工具型微信小程序(Find周邊),里面用到了語音識別技術。現將實現細節(jié)整理如下:

接口預覽

通過閱讀了解科大訊飛接口文檔、小程序接口開發(fā)文檔以及對后端ThinkPhp框架的學習,我整理了如下開發(fā)步驟:

  • 注冊科大訊飛賬號( 國人的驕傲,全球領先的語音識別技術 )
  • 進入AIUI開放平臺在應用管理創(chuàng)建應用并記錄APPID和ApiKey
  • 進入應用配置,配置符合自己的情景模式、識別方式和技能
  • 進行小程序開發(fā)錄制需要識別的音頻(下有詳述)
  • 后端轉碼錄制的音頻(科大訊飛支持pcm、wav),提交給識別接口(下有詳述)
  • 小程序接到識別結果進行接下來業(yè)務

音頻錄制接口

  • wx.startRecord()和wx.stopRecord()

wx.startRecord()和wx.stopRecord()接口也可以滿足需求,但從1.6.0 版本開始不再被微信團隊維護。建議使用能力更強的 wx.getRecorderManager 接口。該接口獲取到的音頻格式為silk。

silk是webm格式通過base64編碼后的結果,我們解碼后需要將webm轉換成pcm、wav

  • wx.getRecorderManager()

相對wx.startRecord()接口,該接口提供的能力更為強大(詳情),可以暫停錄音也可以繼續(xù)錄音,根據自己需求設置編碼碼率,錄音通道數,采樣率。最讓人開心的是可以指定音頻格式,有效值 aac/mp3。不好的是wx.getRecorderManager()在1.6.0才開始被支持。當然如果你要兼容低端微信用戶需要使用wx.startRecord()做兼容處理。

  • 事件監(jiān)聽細節(jié)
// 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;
    }
}


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://www.xiuhaier.com/wxmini/doc/course/24263.html 復制鏈接 如需定制請聯系易優(yōu)客服咨詢:800182392 點擊咨詢
QQ在線咨詢
AI智能客服 ×