微信小程序写一个录音机

微信小程序写一个录音机

代码:

wxml:

html 复制代码
<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:

css 复制代码
.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:

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:

json 复制代码
{
  "usingComponents": {},
  "navigationBarTitleText": "录音机"
}

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

相关推荐
码云数智-园园3 小时前
和小鹅通一样的平台有哪些
微信小程序
吴声子夜歌5 小时前
小程序——逻辑层
小程序
花木偶6 小时前
小迪网安:APP攻防-Day1
安全·小程序
吴声子夜歌1 天前
小程序——生命周期函数和事件处理函数
服务器·前端·小程序
hnxaoli2 天前
win10程序(十六)通达信参数清洗器
开发语言·python·小程序·股票·炒股
码云数智-大飞2 天前
自助建站系统哪个好?快速建站哪个平台好
微信小程序
吴声子夜歌2 天前
小程序——项目结构
小程序
大黄说说2 天前
微信小程序制作平台有哪些?SaaS小程序搭建平台推荐
微信小程序
Lucky小黄人3 天前
微信小程序查看备案号
微信小程序·小程序
码云数智-园园3 天前
小程序制作平台哪个好?微信小程序制作平台对比评测
微信小程序