小程序点击录音--播放录音--停止录音

版权声明:菜鸟老五 https://blog.csdn.net/qq_35695041/article/details/85322792

//WXML
<!-- 外层视图 -->
<view class='cont'>
<!-- 按钮 -->
<view class='cont_btn' wx:for="{{list}}" data-name="{{item.name}}" wx:key="key" bindtap='btn_sub'>{{item.name}}</view>
</view>

//JS

const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()

Page({

  data: {
    list: [{ "name": "播放录音" }, { "name": "停止录音" }, { "name": "点击录音" }]
  },
  /**  
   * 生命周期函数--监听页面加载  
   */
  onLoad: function (options) {
    console.log(recorderManager)
  },
  // 获取当前选项
  btn_sub:function(res){
    var name = res.currentTarget.dataset.name;
    var that=this;
    console.log(res.currentTarget.dataset.name);
    if (name =="停止录音"){
      that.stop();
    } else if (name =="播放录音"){
      that.play();
    } else if (name =="点击录音"){
      that.start();
    }
  },
  //开始录音的时候
  start: function () {
    //https://www.cnblogs.com/danielWise/p/9020884.html
    const options = {
      duration: 10000,//指定录音的时长,单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式,有效值 aac/mp3
      frameSize: 50,//指定帧大小,单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },

  //停止录音
  stop: function () {
    recorderManager.stop();
    recorderManager.onStop((res) => {
      this.tempFilePath = res.tempFilePath;
      console.log('停止录音', res.tempFilePath)
      const { tempFilePath } = res
    })
  },


  //播放声音
  play: function () {
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },


});
//WXSS
/* 外层视图 */
.cont{
width: 100%;
height: 150rpx;
position: absolute;
top: 10%;
text-align: center;
}
/* 按钮样式 */
.cont_btn{
position:relative;
float:left;
width:25%;
height:80rpx;
margin:10rpx 30rpx;
border-radius:10rpx;
line-height:80rpx;
background-color:aquamarine;
font-size:30rpx;
}

猜你喜欢

转载自blog.csdn.net/qq_35695041/article/details/85322792