微信小程序写一个录音机

微信小程序写一个录音机

代码:
wxml:

<view class="container">
  <view class="duration">{{duration}}</view>
  <button bindtap="startRecord" class="btn">开始录音</button>
  <button bindtap="stopRecord" class="btn">停止录音</button>
  <button bindtap="playRecord" class="btn">播放录音</button>
</view>
<audio id="audio" src="{{recordPath}}" controls></audio>

wxss:

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 84vh;
}

.btn {
  margin: 10px;
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
}

.duration {
  margin-top: -50px;
  font-size: 24px;
}

js:

let timer = null;
Page({
  data: {
    isRecording: false,
    recordPath: '',
    duration: '00:00'
  },
  startRecord: function() {
    const recorderManager = wx.getRecorderManager();
    this.setData({
      isRecording: true,
      duration: '00:00'
    });
    let startTime = new Date().getTime();
    timer = setInterval(() => {
      let currentTime = new Date().getTime();
      let diff = currentTime - startTime;
    
      let m = Math.floor(diff / 60000 % 60);
      let s = Math.floor(diff / 1000 % 60);
      this.setData({
        duration: `${this.formatTime(m)}:${this.formatTime(s)}`
      });
    }, 1000);
    recorderManager.start({
      format: 'mp3'
    });
    recorderManager.onStart(() => {
      console.log('recorder start');
    });
    recorderManager.onStop((res) => {
      console.log('recorder stop', res);
      this.setData({
        recordPath: res.tempFilePath,
        isRecording: false
      });
    });
  },
  stopRecord: function() {
    const recorderManager = wx.getRecorderManager();
    clearInterval(timer);
    recorderManager.stop();
  },
  playRecord: function() {
    this.setData({
      // isRecording: true,
      duration: '录音播放'
    });
    const audioCtx = wx.createInnerAudioContext();
    audioCtx.src = this.data.recordPath;
    audioCtx.play();
  },
  formatTime: function(time) {
    return time < 10 ? `0${time}` : time;
  }
});

json:

{
  "usingComponents": {},
  "navigationBarTitleText": "录音机"
}

以上就是实现一个录音机的小程序!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值