JS-SDK front-end speech recognition feature micro enterprise development vue letter (with the public number) based on

JS-SDK front-end speech recognition feature micro enterprise development vue letter (with the public number) based on

Micro-channel JS-SDK

Need to implement a front-end features, such as sound recordings, photographs, sharing, location, etc., we want to implement front-end call these functions must be achieved through JS-SDK way to call, how to use it, this brief introduction (novice the first development summary, not a place we hope to correct me)

1. preparation

Because it is the first time the development, read a lot of documents, including official documents, read many times, still confused, those things with the front end, the rear end of what things do, with no concept. After a lot of trial and collaboration with the back-end, and finally the call is successful!
There is a micro-enterprise application letter with a small program, which the self-built application development with the number of public development, back-end set slightly different
This is the business directory micro letter
back-end : According to micro-enterprises in the bottom of the letter enterprise application id and my business options in the applet Secret self-built applications to obtain token, and calculates the signature series of operations, official documents online are very specific detail, there is not much to say;
configuration
needs to be set in the domain of self-built micro-channel program of the enterprise: this domain is the front end of writing code extranet web domain name, which is the last presentation of the website domain (front-end code is written to the back-end, back-end address according to the project 我的是gitLabconfiguration outside of your domain name), the first configuration needs to start, and so to the back end with the good, there are startup a txt file, need to be packaged front-end to the back end, back-end configuration to the root directory and ensure access to txt file
Here Insert Picture Description
说明:is necessary to configure this domain, only configure this domain can use the domain call JS-SDK, you can use the micro-channel development tools public number of development options for online debugging domain name, 注意:but you can debug package to the external network ip line

Front-end code writing

Installation and set up in the introduction wx

import wx from 'weixin-js-sdk';
const _this = wx;

To a component in the current component introduced on the line, introducing complete is to use, you must complete the registration and other logic before the page call interface, because the recording function is triggered manually executed, so the vue can write a function to perform in the mounted hook function complete the registration code is as follows:

methods: {
      getConfig() {
        const self=this;
        const data=self.qs.stringify({url: location.href.split('#')[0]});//需要传的地址为#前面的地址
        console.log(data);
        self.axios({
          method: 'post',
          url: '',//获取签名等信息的地址
          headers: {'Content-Type': 'application/json'},
          data:data  //向服务端提供授权url参数,并且不需要#后面的部分
        }).then((res) => {
           let list = res.data.data;
          	_this.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: list.appId, // 必填,公众号的唯一标识
            timestamp: list.timestamp, // 必填,生成签名的时间戳
            nonceStr: list.noncestr, // 必填,生成签名的随机串
            signature: list.signature, // 必填,签名
            jsApiList: [
              'startRecord', //开始录音接口
              'stopRecord',// 停止录音接口
              'playVoice', //播放语音接口
              'pauseVoice',//暂停播放接口
              'stopVoice', //停止播放接口
              'uploadVoice',//上传语音接口
              'downloadVoice', //下载语音接口
              'onVoicePlayEnd', // 监听语音播放完毕api
              'translateVoice'
            ] // 必填,需要使用的JS接口列表
          });
          _this.ready(() => {
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
          })
          // 微信sdk错误返回问题
          _this.error((res) => {
            alert('出错了:' + res.errMsg)// 这个地方的好处就是wx.config配置错误,会弹出窗口哪里错误,然后根据微信文档查询即可。
          })
        }).catch((error) => {
          console.log(error)
        })
      },
      // 开始录音
      start(e) {
        let that = this;
        that.stop();
        that.time = 0;
        if(!localStorage.rainAllowRecord || localStorage.rainAllowRecord !== 'true'){
          _this.startRecord({
            success: function () {
              /*console.log('成功开始调起录音')*/
               	that.timer = setInterval(() => {
                that.time++
              }, 1000)
              that.vicoeEnd()
            },
            fail: function () {
            /*console.log('开始录音失败')*/
            },
            cancel: function () {
              alert('用户拒绝授权录音')
            }
          })
        }
      },
      // 停止录音
      stop() {
        let that = this
          _this.stopRecord({
          success: function (res) {
            if(that.time<0.5){
              return
            }
            // alert('暂停成功')
            /*console.log(res, "停止成功");*/
            clearInterval(that.timer)
            that.localId = res.localId
            /*that.upVoice()*/
          },
          fail: function (error) {
            /*console.log(error, "停止失败")*/
          }
        })
      },
      //取消录音判断
      isCancel(e) {
          this.cancel()
      },
      // 取消录音
      cancel() {
        _this.stopRecord({
          success: (res) => {
            /*console.log("取消录音成功");*/
          },
          fail:function (error) {
            console.log("取消录音失败");
          }
        })
      },
      // 60秒监听
      vicoeEnd() {
        let that = this
        _this.onVoiceRecordEnd({
          // 录音时间超过一分钟没有停止的时候会执行 complete 回调
          complete: function (res) {
            alert('60秒停止录音')
            that.localId = res.localId
            clearInterval(that.timer);
            /*that.upVoice()*/
          }
        })
      },
      // 合并
      merge() {
        let that = this
        this.axios({
          method: 'post',
          url: '',
          headers: {'Content-Type': 'application/json'},
          data: {url: location.href.split('#')[0]}
        })
          .then((ser) => {
            console.log(ser)
            that.$refs.allRecord.src = ser.data
          })
          .catch((error) => {
            console.log(error)
          })
      },
      // // 播放
      // play () {
      //   let that = this
      //   console.log(that.localId)
      //   _this.playVoice({
      //     localId: that.localId // 需要播放的音频的本地ID,由stopRecord接口获得
      //   })
      // },
      // // 暂停
      // pausePlay () {
      //   let that = this
      //   _this.pauseVoice({
      //     localId: that.localId // 需要暂停的音频的本地ID,由stopRecord接口获得
      //   })
      // },
      // // 停止
      // stopPlay () {
      //   let that = this
      //   _this.stopVoice({
      //     localId: that.localId // 需要停止的音频的本地ID,由stopRecord接口获得
      //   })
      // },

      //结束录音并识别语音
      translate() {
        const that = this;
        _this.stopRecord({
          success: function (res) {
            /*console.log(res,"翻译前停止录音");*/
            that.localId = res.localId;
            _this.translateVoice({
              localId: that.localId,
              complete: function (res) {
                console.log(res,"调用翻译完成时");
              }
            });
          },
          fail: function (res) {
            console.log(res,"调用停止失败");
          }
        });
      },
      // 上传语音
      upVoice() {
        let that = this
        _this.uploadVoice({
          localId: that.localId, // 需要上传的音频的本地ID,由stopRecord接口获得
          isShowProgressTips: 1, // 默认为1,显示进度提示
          success: function (res) {
            var apiUrl = window.location.href
            /*alert('上传成功')*/
            that.serverId = res.serverId // 返回音频的服务器端ID
            that.axios({
              method: 'post',
              url: 'http://my.service.com/index.php/opcode/6002',
              headers: {'Content-Type': 'application/json'},
              data: {
                serverId: res.serverId,
                url: location.href.split('#')[0]
              }
            })
              .then((data) => {
                console.log(data)
                that.$refs.player.src = data.data
              })
              .catch((error) => {
                console.log(error)
              })
          }
        })
      }
      // 下载语音
      // downVoice () {
      //   let that = this
      //   _this.downloadVoice({
      //     serverId: that.serverId, // 需要下载的音频的服务器端ID,由uploadVoice接口获得
      //     isShowProgressTips: 1, // 默认为1,显示进度提示
      //     success: function (res) {
      //       alert('下载成功')
      //       that.downLoadId = res.localId // 返回音频的本地ID
      //       console.log(res)
      //       console.log(that.downLoadId)
      //     }
      //   })
      // },
      // 模拟上传语音
      // fake () {
      //   var apiUrl = window.location.href
      //   this.axios({
      //     method: 'post',
      //     url: 'api',
      //     headers: {'Content-Type': 'application/json'},
      //     data: {
      //       serverId: '',
      //       url: apiUrl
      //     }
      //   })
      //     .then((res) => {
      //       console.log(res)
      //       this.$refs.player.src = res.data
      //     })
      //     .catch((error) => {
      //       console.log(error)
      //     })
      // }
    },

Here style code needed to write on the line, which need to call recording start button, which button to call the end of the recording, which need to be translated, which function needs to use, direct calls to methods which corresponds to the method, (other JS-SDK If you call, the principle of equal, add functionality to jsApiList array of fields you need for registration 微信公众号API文档可查can be cited), the need to make a corresponding method succeeded things written in the corresponding method where it ok

It is not very simple, finished writing the code is the code package submitted code, background update code to the line, you can see the effects. 注意:Since the micro-channel analog developer tools to debug, we can only have an analog recording results are returned, the real voice and translation have to send the URL to open a micro letter View

Well, the micro-channel JS-SDK interface calls described here, the novice beginning to write, hoping to help to you, also please a lot of guidance

Guess you like

Origin blog.csdn.net/weixin_42204698/article/details/82866026