WeChat applet development combat (28): play, pause, stop sound

Use the wx.playVoice method to play the specified audio file. This method needs to set a filePath attribute to specify the path of the audio file. Use the wx.pauseVoice method to pause the playback of the current audio file. After pausing, call the wx.playVoice method again to resume playback from the paused position. If you want to play an audio file from the beginning, you need to call the wx.stopVoice method to stop the playback of the audio file, and call the wx.playVoice method again to play the audio file from the beginning. The applet only allows one audio file to be played at the same time. If the previous audio is playing while the current audio is playing, the playback of the previous audio will be terminated.

The following code improves the program in the previous section. After stopping the recording, you can play, pause and stop the recorded audio.

index.wxml

<view style="margin:20px">
  <button  bindtap="startRecord">开始录音</button>
  <button style = "margin-top:10px" bindtap="stopRecord">停止录音</button>
  <button style = "margin-top:10px" bindtap="playVoice">播放录音</button>
  <button style = "margin-top:10px" bindtap="pauseVoice">暂停播放</button>
  <button style = "margin-top:10px" bindtap="stopVoice">停止播放</button>
</view>

index.js

var app = getApp()
Page({
  data: {
    recording: false,
    playing: false,
    hasRecord: false,
  },
  //开始录音
  startRecord: function () {
    var that = this;
    wx.startRecord({
      success: function (res) {
        console.log(res.tempFilePath);
        that.setData({
          hasRecord: true,
          tempFilePath: res.tempFilePath,
        })
      },
      complete: function () {
        that.setData({ recording: false })
      }
    })
  },
  //  停止录音
  stopRecord: function () {
    var that = this;
    console.log(this.data.tempFilePath);
    wx.stopRecord({
      success: function () {
        console.log('stop record success')
        that.setData({
          recording: false,
          hasRecord: false,
        })
      }
    })
  },
  //  开始播放录制的音频
  playVoice: function () {
    var that = this;
    wx.playVoice({
      filePath: this.data.tempFilePath,
      success: function () {
        console.log('play voice finished')
        that.setData({
          playing: false,
        })
      }
    })
  },
   //  暂停播放录制的音频
  pauseVoice: function () {
    wx.pauseVoice()
    this.setData({
      playing: false
    })
  },
  //  停止播放录制的音频
  stopVoice: function () {
    this.setData({
      playing: false,
 
    })
    wx.stopVoice()
  }
})

Guess you like

Origin blog.csdn.net/nokiaguy/article/details/108396383