微信小程序写一个录音机

微信小程序写一个录音机

代码:

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": "录音机"
}

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

相关推荐
鸭鸭梨吖2 小时前
微信小程序---下拉框
微信小程序·小程序
CRMEB定制开发3 小时前
CRMEB Pro版前端环境配置指南
前端·微信小程序·uni-app·商城源码·微信商城·crmeb
mon_star°5 小时前
搭建一款结合传统黄历功能的日历小程序
微信·微信小程序·小程序·微信公众平台
The_era_achievs_hero6 小时前
微信小程序91~100
微信小程序·小程序
假装我不帅6 小时前
微信小程序下拉加载更多实现
微信小程序·小程序
高压锅_12206 小时前
Cursor+Coze+微信小程序实战: AI春联生成器
人工智能·微信小程序·notepad++
2301_805962936 小时前
微信小程序控制空调之微信小程序篇
微信小程序·小程序
Ama_tor12 小时前
mini-program01の系统认识微信小程序开发
微信小程序·小程序
毛毛三由21 小时前
基于svga+uniapp的微信小程序动画组件开发指南
微信小程序·uni-app·notepad++