首頁  >  文章  >  微信小程式  >  小程式實現語音辨識經驗分享

小程式實現語音辨識經驗分享

小云云
小云云原創
2018-02-08 16:02:036582瀏覽

之前寫了個工具型微信小程式(Find週邊),裡面用到了語音辨識技術。本文就主要和大家分享小程式實現語音辨識經驗,希望能幫助大家。

介面預覽  

透過閱讀了解科大訊飛介面文件、小程式介面開發文件以及對後端ThinkPhp框架的學習,我整理瞭如下開發步驟:

  • 註冊科大訊飛帳號(國人的驕傲,全球領先的語音辨識技術)

  • 進入AIUI開放平台在應用程式管理創建應用程式並記錄APPID和ApiKey

  • 進入應用程式配置,配置符合自己的情境模式、辨識方式和技能

  • 進行小程式開發錄製需要識別的音訊(下有詳述)

  • 後端轉碼錄製的音訊(科大訊飛支援pcm、wav),提交給識別介面(下有詳述)

  • 小程式接到識別結果進行接下來業務

音訊錄製介面

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

wx.startRecord()和wx.stopRecord()介面也可以滿足需求,但從1.6.0 版本開始不再被微信團隊維護。建議使用能力較強的 wx.getRecorderManager 介面。此介面所取得的音訊格式為silk。
silk是webm格式經過base64編碼後的結果,我們解碼後需要將webm轉換成pcm、wav
  • wx.getRecorderManager()

相對wx.startRecord()接口,該接口提供的能力更為強大(詳情),可以暫停錄音也可以繼續錄音,根據自己需求設置編碼碼率,錄音通道數,採樣率。最讓人開心的是可以指定音訊格式,有效值 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("结束")
    //触发录音停止
    recorderManager.stop()
  }
})

//wxml:
<view bindtouchstart=&#39;startHandel&#39; bindtouchend=&#39;endHandle&#39; 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[&#39;viceo&#39;];
        $tempfile = file_get_contents($upload_res[&#39;tmp_name&#39;]);
        $wavname = substr($upload_res[&#39;name&#39;],0,strripos($upload_res[&#39;name&#39;],".")).".wav";
        $arr = explode(",", $tempfile);
        $path = &#39;Aduio/&#39;.$upload_res[&#39;name&#39;];
        
        if ($arr && !empty(strstr($tempfile,&#39;base64&#39;))){
            //微信模拟器录制的音频文件可以直接存储返回
            file_put_contents($path, base64_decode($arr[1]));
            $data[&#39;path&#39;] = $path;
            apiResponse("success","转码成功!",$data);
        }else{
            //手机录音文件
            $path = &#39;Aduio/&#39;.$upload_res[&#39;name&#39;];
            $newpath = &#39;Aduio/&#39;.$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[&#39;path&#39;] = $newpath;
                apiResponse("success","转码成功!",$data);
            }
        }
        apiResponse("error","发生未知错误!");
    }
    //json数据返回方法封装
    function apiResponse($flag = &#39;error&#39;, $message = &#39;&#39;,$data = array()){
        $result = array(&#39;flag&#39;=>$flag,'message'=>$message,'data'=>$data);
        print json_encode($result);exit;
    }
}

呼叫識別介面

當我們把檔案準備好之後,接下來我們就可以將base64編碼之後的音訊檔案透過api介面請求傳輸過去。期間我們要注意嚴格依照文檔中所說的規範傳輸,否則將造成不可知的結果。

<?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(
            &#39;X-Appid:&#39;.$Appid,
            &#39;X-CurTime:&#39;.$curtime,
            &#39;X-CheckSum:&#39;.$CheckSum,
            &#39;X-Param:&#39;.$xparam,
            &#39;Content-Type:&#39;.&#39;application/x-www-form-urlencoded; charset=utf-8&#39;
            );
        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(&#39;scene&#39; => '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;
    }
}

到這裡基本上就完成了。以上程式碼是經過整理之後的,不一定能滿足各位的實際開發需求。如果發現不當之處歡迎微信交流(xiaoqiang0672)。

想看實際案例的可以微信掃碼
-
小程式實現語音辨識經驗分享

#相關推薦:

. Net開發微信公眾平台語音辨識程式碼解析

關於微信公眾平台語音辨識結果的呼叫

HTML5語音辨識標籤寫法附圖_html5教學技巧

以上是小程式實現語音辨識經驗分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn