微信小程序實現錄音Record功能

本文實例為大傢分享瞭微信小程序實現錄音Record功能的具體代碼,供大傢參考,具體內容如下

佈局

<!--pages/record/record.wxml-->
<view>
 <button 
  class="tui-menu-list"
  bindtap="startRecordAac" 
  type="primary">錄音開始(aac)</button>
 <button 
  class="tui-menu-list"
  bindtap="startRecordMp3" 
  type="primary">錄音開始(mp3)</button>
 <button 
  class="tui-menu-list" 
  bindtap="stopRecord" 
  type="primary">錄音結束</button>
 <button 
  class="tui-menu-list"
  bindtap="playRecord" 
  type="primary">播放錄音</button>
</view>

樣式:

/* pages/record/record.wxss */
 
.tui-menu-list{
  flex-direction: row;
  margin: 20rpx;
  padding: 20rpx;
}

開始錄音和停止錄音

// pages/record/record.js
Page({
 
  /**
   * 頁面的初始數據
   */
  data: {
 
  },
 
  onLoad:function (options) {
    var that = this
    this.recorderManager = wx.getRecorderManager();
    this.recorderManager.onError(function () {
      that.tip("錄音失敗!");
    })
    this.recorderManager.onStop(function (res) {
      that.setData({
        src:res.tempFilePath
      })
      console.log(res.tempFilePath)
      that.tip("錄音完成!")
    })
    this.innerAudioContext = wx.createInnerAudioContext()
    this.innerAudioContext.onError((res) =>{
      that.tip("播放錄音失敗!")
    })
  },
 
  //提示
  tip:function (msg) {
    wx.showModal({
      cancelColor: 'cancelColor',
      title:'提示',
      content:msg,
      showCancel:false
    })
  },
 
  //錄制aac
  startRecordAac:function () {
    this.recorderManager.start({
      format:'aac'
    })
  },
 
  //錄制mp3
  startRecordMp3:function () {
    this.recorderManager.start({
      format:'mp3'
    })
  },
 
  //停止錄音
  stopRecord:function () {
    this.recorderManager.stop()
  },
 
  //播放錄音
  playRecord:function () {
    var that = this
    var src = this.data.src
    if (src='') {
      this.tip('請先錄音')
      return
    }
    this.innerAudioContext.src = this.data.src
    this.innerAudioContext.play()
  }
 
  
})

效果圖:

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: