微信公众号jssdk音频

首先在微信公众号配置安全域名

还需在前端页面引入<script src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>,支持https

附上前端代码:

$.ajax({
          type: 'post',
          url: '{:U(\'Newsystem/represen\')}',
          data: {url:encodeURIComponent(location.href.split('#')[0])},
          async: true,
          success: function (res) {
              // console.log(res);
              wx.config({
                  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                  appId: res.appid, // 必填,公众号的唯一标识
                  timestamp: res.timestamp, // 必填,生成签名的时间戳
                  nonceStr: res.noncestr, // 必填,生成签名的随机串
                  signature: res.signature,// 必填,签名
                  jsApiList: ['startRecord','stopRecord','onVoiceRecordEnd','playVoice','pauseVoice','stopVoice','onVoicePlayEnd','uploadVoice','downloadVoice','translateVoice'] // 必填,需要使用的JS接口列表
              });
              wx.ready(function () {
                  // console.log('success');
                  if (localStorage.allowRecord !== 'true') {
                      wx.startRecord({
                          success: function() {
                              localStorage.allowRecord = 'true';
                              // 仅仅为了授权,所以立刻停掉
                              wx.stopRecord();
                          },
                          cancel: function() {
                              alert('用户拒绝授权录音');
                          }
                      });
                  }
              });
              wx.error(function (res) {
                  // console.log(res);
              });
          },
          error: function (res) {
              alert('操作失败');
          }
      });
      var localId;
      var btnRecord = $('#voice');
      btnRecord.on('touchstart', function(event) {
          // console.log(event);
          event.preventDefault();
          btnRecord.addClass('hold');
          startTime = new Date().getTime();
          // 延时后录音,避免误操作
          recordTimer = setTimeout(function() {
              wx.startRecord({
                  success: function() {
                  },
                  cancel: function() {
                      alert('用户拒绝授权录音');
                  }
              });
          }, 300);
      }).on('touchend', function(event) {
          event.preventDefault();
          btnRecord.removeClass('hold');
          // 间隔太短
          if (new Date().getTime() - startTime < 300) {
              startTime = 0;
              // 不录音
              clearTimeout(recordTimer);
          } else if(new Date().getTime() - startTime > 120000){
              alert('录音时间不得超过两分钟');
              startTime = 0;
              // 不录音
              clearTimeout(recordTimer);
          }else { // 松手结束录音
              wx.stopRecord({
                  success: function(res) {
                      localId = res.localId;
                      wx.translateVoice({
                          localId: localId, // 需要识别的音频的本地Id,由录音相关接口获得
                          isShowProgressTips: 1, // 默认为1,显示进度提示
                          success: function (res) {
                              $('textarea[name=digest]').val(res.translateResult);// 语音识别的结果
                          }
                      });
                      // 上传到服务器
                      uploadVoice();
                  },
                  fail: function(res) {
                      alert(JSON.stringify(res));
                  }
              });
          }
      });
      //上传录音
      function uploadVoice(){
          //调用微信的上传录音接口把本地录音先上传到微信的服务器
          //不过,微信只保留3天,而我们需要长期保存,我们需要把资源从微信服务器下载到自己的服务器
          wx.uploadVoice({
              localId: localId, // 需要上传的音频的本地ID,由stopRecord接口获得
              isShowProgressTips: 1, // 默认为1,显示进度提示
              success: function (res) {
                  //把录音在微信服务器上的id(res.serverId)发送到自己的服务器供下载。
                  console.log(res);
                  if(res.serverId === undefined){
                      alert('上传失败');
                  }else {
                      $('#hidden').val(res.serverId);
                  }
              }
          });
      }

附上后端代码:

//配置jssdk
    public function represen(){
        $wx['timestamp'] = time();
        $wx['noncestr'] = md5(time());
        $wx['jsapi_ticket'] = $this->actionTicket();
        $wx['url'] = urldecode(I('url','','trim'));
        $string = sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", $wx['jsapi_ticket'], $wx['noncestr'], $wx['timestamp'], $wx['url']);
        //生成签名
        $wx['signature'] = sha1($string);
        $wx['appid'] = 你的appid;
        $this->ajaxReturn($wx);
    }
    public function actionAccessToken(){
        if (session('access_token') && session('time') > time()){
            return session('access_token');
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的appid&secret=你的appsecret";
        $info = file_get_contents($url);
        $info = json_decode($info,1);
        if ($info){
            $info['time'] = time()+$info['expires_in']-200;
            session('time',$info['time']);
            session('access_token',$info['access_token']);
            return $info['access_token'];
        }else{
            return '失败';
        }
    }
    public function actionTicket()
    {
        if (session('ticket') && session('ticketTime') > time()){
            return session('ticket');
        }
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$this->actionAccessToken()."&type=jsapi";
        $info = file_get_contents($url);
        $info = json_decode($info,1);
        if ($info){
            $info['time'] = time()+$info['expires_in']-200;
            session('ticketTime',$info['time']);
            session('ticket',$info['ticket']);
            return $info['ticket'];
        }else{
            return '失败';
        }
    }

这里只有配置好jssdk并把音频上传到微信服务器上代码,后续思路是将前端上传到微信服务器上的serverId放到表单中,提交表单时把serverId提交到后端,在后端用该值在微信服务器上下载该音频,下载下来需要转格式(该步骤挺麻烦的,放弃做的原因)转好格式之后放在自己的服务器上,把该地址存到数据库中就好了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Vue2中接入微信公众号JSSDK,您需要按照以下步骤进行操作: 1. 在公众号后台配置JS接口安全域名,确保您的域名已经添加到了微信公众平台的安全域名列表中。 2. 安装使用`weixin-js-sdk`库,可以通过npm进行安装: ``` npm install weixin-js-sdk ``` 3. 在需要使用JSSDK的组件或页面中引入`weixin-js-sdk`库: ```javascript import wx from 'weixin-js-sdk'; ``` 4. 在组件或页面的`mounted`生命周期钩子函数中初始化JSSDK,并进行相关配置: ```javascript mounted() { this.initWeChatJSSDK(); }, methods: { initWeChatJSSDK() { // 异步请求后端接口获取微信配置信息 axios.get('/api/getWeChatConfig') .then(response => { const { appId, timestamp, nonceStr, signature } = response.data; wx.config({ debug: false, appId, timestamp, nonceStr, signature, jsApiList: ['chooseImage', 'scanQRCode'] // 需要使用的JSSDK接口 }); wx.ready(() => { // JSSDK配置成功后的回调函数 console.log('JSSDK配置成功'); }); wx.error((res) => { // JSSDK配置失败后的回调函数 console.error('JSSDK配置失败', res); }); }) .catch(error => { console.error('获取微信配置信息失败', error); }); } } ``` 5. 在需要使用JSSDK的地方调用对应的接口,比如选择图片接口`chooseImage`: ```javascript methods: { chooseImage() { wx.chooseImage({ count: 1, success: function (res) { // 选择图片成功后的处理逻辑 const localIds = res.localIds; // ... }, fail: function (error) { // 选择图片失败后的处理逻辑 console.error('选择图片失败', error); } }); } } ``` 以上是在Vue2中接入微信公众号JSSDK的基本步骤,您可以根据实际需求进行相应的配置和调用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值