您现在的位置是:首页 > 技术分享

微信语音录入实例分享
wangzhen2018-08-09285人围观

    1、引入js文件

    <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>

    2、生成相关参数

    session_start();
    header('Content-Type:text/html; charset=utf-8');
    $appid = "appid";
    $time = time();
    $arr = array_merge(range("a", "z"),range("A", "Z"),range(0, 9));
    shuffle($arr);
    $nonceStr = substr(join("", $arr), mt_rand(0,12),16);
    
    $protocol=(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
     
    $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    
    if($_SESSION['access_token'] && $_SESSION['expire_access_token'] > time()){
        $access_token = $_SESSION['access_token'];
    } else {
    
        $access_url = "https://api.weixin.qq.com/cgi-bin/token";
        $data = array(
        "grant_type"=>"client_credential",
        "appid"=>$appid,
        "secret"=>"secret"
        );
        $access_url =$access_url."?".http_build_query($data);
        $accessArr = CurlGet($access_url);
        $access_token = $accessArr['access_token'];
        $_SESSION['access_token'] = $access_token;
        $_SESSION['expire_access_token'] = time()+7000;
    }
     
    if($_SESSION['jsapi_ticket'] && $_SESSION['jsapi_ticket_time'] > time()){
        $ticket = $_SESSION['jsapi_ticket'];
    } else {
        $ticket_url= "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
        
        $result = CurlGet($ticket_url);
        
        $ticket = $result['ticket'];
        
        $_SESSION['jsapi_ticket'] = $ticket;
        $_SESSION['jsapi_ticket_time'] = time()+7000;
    }
     
    $signature = "jsapi_ticket=$ticket&noncestr=$nonceStr×tamp=$time&url=$url";
    $sign = sha1($signature);

    3、调用js进行录音并上传

    <input type="button" id="record" style="background:url(/public/common/image/voice_n_1.png) no-repeat center ; background-size:cover;">
    var btnRecord = $('#record');
    var startTime = 0;
    var recordTimer = 300;
    wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
        appId: '<?php echo $appid ?>', // 必填,公众号的唯一标识
        timestamp:'<?php echo $time ?>', // 必填,生成签名的时间戳
        nonceStr: '<?php echo $nonceStr ?>', // 必填,生成签名的随机串
        signature: '<?php echo $sign?>',// 必填,签名
        jsApiList: [
            "startRecord",
            "stopRecord",
            "onVoiceRecordEnd",
            "playVoice",
            "pauseVoice",
            "stopVoice",
            "onVoicePlayEnd",
            "uploadVoice",
            "downloadVoice",
            ] // 必填,需要使用的JS接口列表
    });
     
    wx.ready(function () {
        btnRecord.on('touchstart', function (event) {
             event.preventDefault();
             startTime = new Date().getTime();
             // 延时后录音,避免误操作
             recordTimer = setTimeout(function () {
                 wx.startRecord({
                     success: function (res) {
                        localStorage.rainAllowRecord = 'true';
                     },
                     cancel: function () {
                        alert('没有权限');
                     }
                 });
     
             }, 300);
             wx.onVoiceRecordEnd({
                 //录音时间超过一分钟没有停止的时候会执行 complete 回调
                 complete: function (res) {
                     var localId = res.localId;
                     uploadVoice(localId);
                 }
             });
         })
         btnRecord.on('touchend', function (event) {
             event.preventDefault();
             // 间隔太短
             if (new Date().getTime() - startTime < 300) {
                 tishi('时间短');
                 startTime = 0;
                 // 不录音
                 clearTimeout(recordTimer);
             } else { // 松手结束录音
                 wx.stopRecord({
                     success: function (res) {
                         var localId = res.localId;
                         // 上传到服务器
                         uploadVoice(localId);
                     },
                     fail: function (res) {
                         alert(JSON.stringify(res));
                     }
                 });
             }
         });
     
         function uploadVoice(localId){
             $('#playVoice').val(localId);
             $("#miaoshu").css("display","");
             wx.uploadVoice({
                 localId: localId, // 需要上传的音频的本地ID,由stopRecord接口获得
                 isShowProgressTips: 1, // 默认为1,显示进度提示
                 success: function (res) {
                     var serverId = res.serverId; // 返回音频的服务器端ID
                     $.ajax({
                         url: 'url',
                         type: 'post',
                         data: {serverId: serverId, token: '<?php echo $token; ?>'},
                         dataType: "json",
                         success: function (data) {
                             alert('上传成功');
                         },
                         error: function (xhr, errorType, error) {
                             console.log(error);
                         }
                     });
                 }
             });
         }
     
         document.querySelector('#playrecord').onclick = function() {
             var playlocalId = $('#playVoice').val();
             wx.playVoice({
                 localId: playlocalId
             });
         };
     
         //注册微信播放录音结束事件【一定要放在wx.ready函数内】
         wx.onVoicePlayEnd({
             success: function (res) {
                     stopWave();
             }
         });
     });

    4、后台接收

    //oss上传
    $this->load->library("aliyunoss/samples/Common");
    $ossClient = Common::getOssClient();
     
    $save_audio="/audio";//本地暂时存放的文件夹
    $audio_name=time().".amr";//暂时存放的文件名称
    $filePath="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$access_token&media_id=$serverId";
    $Arrinfo = getFilepapers($filePath,$save_audio,$audio_name);//下载到服务器
     
    $res = $ossClient->uploadFile($bucket, 'audio/'.$file, $Arrinfo['save_path']);
    /**
      * 获取微信远程资源
    */
    function getFilepapers($url,$save_dir='',$filename='',$type=0){
     
       if(trim($url)==''){
          return false;
       }
       if(trim($save_dir)==''){
          $save_dir='./';
       }
       if(0!==strrpos($save_dir,'/')){
          $save_dir.='/';
       }
       //创建保存目录
       if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
          return false;
       }
       //删除原来的文件
       unlink($save_dir . "/".$filename);
       //获取远程文件所采用的方法
       if($type){
          $ch=curl_init();
          $timeout=5;
          curl_setopt($ch,CURLOPT_URL,$url);
          curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
          curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
          $content=curl_exec($ch);
          curl_close($ch);
       }else{
          ob_start();
          readfile($url);
          $content=ob_get_contents();
          ob_end_clean();
       }
       $size=strlen($content);
       //文件大小
     
       $fp2=@fopen($save_dir.$filename,'a');
       fwrite($fp2,$content);
       close($fp2);
       unset($content,$url);
       return array('file_name'=>$filename,'save_path'=>$save_dir.$filename);
    }


文章评论