Wechat jsdk recording function

Requirement description
Create an H5 page, open it and record, and submit the recording file to the background





The maximum duration of wechat recording is 1min

Wechat official document audio interface
The code is as follows

    // isVoice: 0-not recorded 1-in recording 2-finished recording 
    //  Click the recording / recording button to display
      <div class="vm-voice-box" v-show="isVoice < 2">
        <p v-show="!isVoice" @click="voiceStart">Click recording</p>
        <img v-show="isVoice" @click="voiceEnd" src="../../xxx/ico-voice.png" alt="">
      </div>
      
    //  Islisten / / 0 - no audition / end of Audition 1 - audition in progress 2 - pause audition
    //  Recording completion button display
      <div class="vm-voice-player" v-show="isVoice ==  2">
        <div class="vm-vp-button">
          <p class="vm-vp-revoice" @click="openMask(0)">Re record</p>
          <p class="vm-vp-submit" :class="{'vm-vp-no-submit' : isSubmit}" @click="openMask(1)">Submission</p>
          <p class="vm-vp-pause" v-show="!isListen" @click="play">Audition</p>
          <p class="vm-vp-pause" v-show="isListen==1" @click="pause">| |</p>
          <p class="vm-vp-pause vm-vp-border" v-show="isListen==2" @click="play"> ▶ </p>
        </div>
      </div>
      
      data() {
          return {
            id: '',
            startTime: 0,
            recordTimer: null,
            localId: '', // Recording local id
            serverId: '', // Recording wechat service id
            showMask: false,
            tip: 1, //Submit 0-re record
            isVoice: 0, // 0-not recorded 1-in recording 2-finished recording
            isListen: 0, // 0 - no audition / end of Audition 1 - in audition 2 - pause audition
            data1: 0,
            work: {},
            isPlay: false,  // Is it playing?
            isSubmit: false, // Submitted or not
          }
     }
      
      
      // WeChat configuration
      getConfig() {
        let _url = encodeURIComponent(window.location.href)
        // The background provides the interface, passing in the current URL (return the basic configuration information)
        voiceApi.wechatConfig(_url)
        .then(res => {
            if (res.data.code == 200) {
              wx.config({
                debug: false,
                appId: res.data.content.appid,
                timestamp: res.data.content.timestamp, // Required, generate signature timestamp
                nonceStr: res.data.content.nonceStr, // Required, generate random string of signature
                signature: res.data.content.signature, // Required, signature
                // api interfaces requiring authorization
                jsApiList: [
                    'startRecord', 'stopRecord', 'onVoiceRecordEnd', 'uploadVoice', 'downloadVoice', 'playVoice', 'pauseVoice', 'onVoicePlayEnd'
                ]
              })
          wx.ready( () => {
            wx.onVoiceRecordEnd({
                // The complete callback will be executed when the recording time exceeds one minute and does not stop
                complete: function (res) {
                  _this.isVoice = 2
                  _this.localId = res.localId;
                }
            })
          })
        }
    })
  },
  // Start recording
  voiceStart(event) {
    let _this = this
    event.preventDefault()
    // Recording after delay to avoid misoperation
    this.recordTimer = setTimeout(function() {
      wx.startRecord({
        success: function() {
          _this.startTime = new Date().getTime()
          _this.isVoice = 1
        },
        cancel: function() {
          _this.isVoice = 0
        }
      })
    }, 300)
  },
  // Stop recording
  voiceEnd(event) {
    this.isVoice = 2
    let _this = this
    event.preventDefault()
    // The interval is too short.
    if (new Date().getTime() - this.startTime < 300) {
      this.startTime = 0
      // No recording
      clearTimeout(this.recordTimer)
    } else {
      wx.stopRecord({
        success: function(res) {
        // The localId generated by wechat. At this time, the voice has not been uploaded to the wechat server
          _this.localId = res.localId
        },
        fail: function(res) {
          console.log(JSON.stringify(res))
        }
      })
    }
  },
  
  // Audition
  tryListen() {
    let _this = this
    wx.playVoice({
      localId: _this.localId // The local ID of the audio to be played is obtained by the stopRecord interface
    })
    console.log('Listen...')
    wx.onVoicePlayEnd({  // End of listening and playing
        success: function (res) {
          console.log('End of listening')
          _this.isListen = 0
        }
    });
  },
  // Stop listening
  tryStop() {
    let _this = this
    wx.pauseVoice({
      localId: _this.localId // The local ID of the audio to be stopped is obtained by the stopRecord interface
    })
  },
  
  
  // Processing recording data
  voiceHandle() {
    let _this = this
    wx.uploadVoice({
      localId: this.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) {
      // Wechat voice has been uploaded to wechat server and returned a server id
        _this.serverId = res.serverId; // Return the server ID of the audio
        _this.upVoice()
      }
    })
  },
  // Own background upload interface
  upVoice() {
    let data = {
      id: this.id,
      serviceId: this.serverId
    }
    voiceApi.upVoice(data)
    .then(res => {
      if(res.data.code == 200) {
        // !! todo hide loading
        this.isSubmit = true
        this.$Message.message('Submit successfully')
        this.closeMask()
      } else {
        this.$Message.message(res.data.message)
      }
    })
    .catch(err => {
      console.log(err)
    })
  },
**1. Wechat jsdk configuration**
**2. Call the wechat recording start method wx.startRecord**
**3. Call the end method of wechat recording wx.stopRecord**
Return a local audio ID localid after success
 ⚠⚠ if you do not call the recording end method, it will automatically end after recording for 1min, and wx.onVoiceRecordEnd is required to monitor the recording end
 **4. Upload the recording to the wechat server wx.uploadVoice**
Return serverId
 ⚠ wechat has a limited storage time and a validity period of 3 days
 ⚠ at present, the frequency of multimedia file download interface is limited to 10000 times / day. If you need to increase the frequency, please log in wechat public platform and apply for increasing the temporary upper limit in the development interface permission list.
**5. Call your own background to upload to your own server**
This one can be seen as: pass the serverId to your server, and then your server calls the interface provided by wechat to download (serverId) to your server for storage

Tags: Javascript JSON

Posted on Sat, 02 Nov 2019 23:22:42 -0700 by Aeolus