vue uses Weixin SDK recording function

Keywords: SDK axios JSON Vue

Just graduated, entered the company, met the first vue project, using Weixin SDK JS to do the recording function, so started the research journey, after a long time of research, finally, Zen realized a little bit of fur
Many experiments, failures, summary: Weixin JS SDK is to be used online, and can only be used on wechat. It's not easy to say more, and it's not easy to use it on dry goods

Official use instruction document address

https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

Dry goods now

The first step must be to install the sdk first

npm install weixin-js-sdk

Import in the used file

import wx from 'weixin-js-sdk'

I wrote a little dome code and presented it
Stop uploading for recording
In order to save the recording permanently, the recording will also be sent to the back end, and the back end will be converted into an MP3 file to return to the address
Another one is added to combine all the recordings into a long audio to return

<template>
  <div class="hello">
    <button  class="record" @click="start">Start recording</button>
    <button @click="stop">Stop recording</button>
    <button @click="cancel">cancel recording</button>
    <!-- <button @click="play">Playback recording</button>
    <button @click="pausePlay">Pause playback</button>
    <button @click="stopPlay">stop playing</button> -->
    <!-- <button @click="upVoice">Uploading voice</button>
    <button @click="downVoice">Download recording</button> -->
    <!-- <button @click="fake">false</button> -->
    <!-- <button @click="setTime">Start timing</button>
    <button @click="creamTime">Stop timing</button> -->
    <br>
    <p>Recording time{{time}}</p>

    <div class="list">
        //Language just recorded
        <audio ref="player" src=""  controls></audio>
        <!-- ./status/uploads/record/cplZxG7oYspQxopQIb9g_cUJ7Y69htn_ybzFiRZR_U3Vf8Bv4Nh6D6TBPWa5VmGs.mp3 -->
    </div>
    <br>
    <br>
    <div>
      <button @click="merge">Merge all recordings</button>
       <audio ref="allRecord" src=""  controls></audio>
    </div>
  </div>
</template>

<script>
import wx from 'weixin-js-sdk'
const _this = wx
export default {
  name: 'HelloWorld',
  data () {
    return {
      localId: '',
      serverId: '',
      downLoadId: '',
      Soff: true,
      time: 0,
      timer: null
    }
  },
  created () {
    var apiUrl = window.location.href
    // let apiUrl = 'http://weixin.lostars.cn'
    this.axios({
      method: 'post',
      url: 'api', // Write to api
      headers: {'Content-Type': 'application/json'},
      data: {
        url: apiUrl
      }
    })
      .then((res) => {
        // console.log(res)
        let list = res.data.msg
        _this.config({
          debug: false, // When debugging mode is turned on, the return values of all the APIs called will be alert ed out on the client side. To view the parameters passed in, you can open them on the pc side, and the parameter information will be printed out through the log, which will only be printed on the pc side.
          appId: list.appId, // Required, the only sign of the public number.
          timestamp: list.timestamp, // Required, generate signature timestamp
          nonceStr: list.nonceStr, // Required, generate random string of signature
          signature: list.signature, // Required, signature
          jsApiList: ['startRecord', 'stopRecord', 'playVoice', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice', 'downloadVoice'] // Required, list of JS interfaces to be used
          // Interface start recording interface stop recording interface play voice interface pause playing interface stop playing interface upload voice interface download voice interface recognize audio and return to recognition result interface
        })
        // Do not execute until the config information is verified
        _this.ready(() => {

        })
        // Wechat sdk error return problem
        _this.error((res) => {
          alert('Wrong:' + res.errMsg)// The advantage of this place is that the configuration of wx.config is wrong, a pop-up window will pop up where the error is, and then query according to the wechat document.
        })
      })
      .catch((error) => {
        console.log(error)
      })
  },
  methods: {
    // Start recording
    start (e) {
      let that = this
      that.time = 0
      _this.startRecord({
        success: function () {
          // alert('recording successfully started ')
          that.timer = setInterval(() => {
            that.time++
          }, 1000)
          that.vicoeEnd()
        },
        cancel: function () {
          alert('User refuses to authorize recording')
        }
      })
    },
    // Stop recording
    stop () {
      let that = this
      // clearInterval(that.timer)
      _this.stopRecord({
        success: function (res) {
          // alert('pause succeeded ')
          console.log(res)
          clearInterval(that.timer)
          that.localId = res.localId
          that.upVoice()
        },
        fail: function (error) {
          // alert('I can't stop when I'm dead ')
          console.log(error)
        }
      })
    },
    // cancel recording
    cancel () {
      _this.stopRecord({
        success: (res) => {

        }
      })
    },
    // 60 second monitoring
    vicoeEnd () {
      let that = this
      _this.onVoiceRecordEnd({
        // The complete callback will be executed when the recording time exceeds one minute and does not stop
        complete: function (res) {
          alert('60 Seconds to stop recording')
          that.localId = res.localId
          clearInterval(that.timer)
          that.upVoice()
        }
      })
    },
    // merge
    merge () {
      let that = this
      var apiUrl = window.location.href
      this.axios({
        method: 'post',
        url: 'http://apiwx.lostars.cn/index.php/index/File/merge',
        headers: {'Content-Type': 'application/json'},
        data: {
          url: apiUrl
        }
      })
        .then((ser) => {
          console.log(ser)
          that.$refs.allRecord.src = ser.data
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // / / play
    // play () {
    //   let that = this
    //   console.log(that.localId)
    //   _this.playVoice({
    //     localId: that.localId / / the local ID of the audio to be played, obtained by the stopRecord interface
    //   })
    // },
    // / / pause
    // pausePlay () {
    //   let that = this
    //   _this.pauseVoice({
    //     localId: that.localId / / the local ID of the audio to be paused, obtained by the stopRecord interface
    //   })
    // },
    // / / stop
    // stopPlay () {
    //   let that = this
    //   _this.stopVoice({
    //     localId: that.localId / / the local ID of the audio to be stopped, obtained by the stopRecord interface
    //   })
    // },
    // Uploading voice
    upVoice () {
      let that = this
      _this.uploadVoice({
        localId: that.localId, // The local ID of the audio to be uploaded is obtained by the stopRecord interface
        isShowProgressTips: 1, // Default is 1, display progress prompt
        success: function (res) {
          var apiUrl = window.location.href
          alert('Upload success')
          that.serverId = res.serverId // Return the server ID of the audio
          that.axios({
            method: 'post',
            url: 'api',
            headers: {'Content-Type': 'application/json'},
            data: {
              serverId: res.serverId,
              url: apiUrl
            }
          })
            .then((data) => {
              console.log(data)
              that.$refs.player.src = data.data
            })
            .catch((error) => {
              console.log(error)
            })
        }
      })
    }
    // Download voice
    // downVoice () {
    //   let that = this
    //   _this.downloadVoice({
    //     serverId: that.serverId, / / the server ID of the audio to be downloaded, obtained by the uploadVoice interface
    //     isShowProgressTips: 1, / / the default is 1, displaying progress tips
    //     success: function (res) {
    //       alert('download succeeded ')
    //       that.downLoadId = res.localId / / returns the local ID of the audio
    //       console.log(res)
    //       console.log(that.downLoadId)
    //     }
    //   })
    // },
    // Analog upload voice
    // fake () {
    //   var apiUrl = window.location.href
    //   this.axios({
    //     method: 'post',
    //     url: 'api',
    //     headers: {'Content-Type': 'application/json'},
    //     data: {
    //       serverId: 'cplZxG7oYspQxopQIb9g_cUJ7Y69htn_ybzFiRZR_U3Vf8Bv4Nh6D6TBPWa5VmGs',
    //       url: apiUrl
    //     }
    //   })
    //     .then((res) => {
    //       console.log(res)
    //       this.$refs.player.src = res.data
    //     })
    //     .catch((error) => {
    //       console.log(error)
    //     })
    // }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>

</style>

The contents of config need to be read carefully. Just follow that step
If you have any doubts, please leave a message to discuss

Posted by xcoderx on Sun, 05 Jan 2020 18:07:23 -0800