项目需求
在做一个项目时需要有这样的功能:用户可以通过微信小程序录音且录音完成后可以播放自己的录音。
项目实施
首先,在前端界面上绘制几个按钮,分别添加上点击事件。
index.wxml
<!--index.wxml--> <view class="container"> <button type="primary" bindtap="start">开始录音</button> <button type="primary" bindtap="suspend">录音暂停</button> <button type="primary" bindtap="continue">继续录音</button> <button type="primary" bindtap="stop">录音停止</button> <button type="primary" bindtap="play">播放录音</button> </view>
讯享网
index.wxss
讯享网/index.wxss/ button {
margin: 20rpx; font-size: 30rpx; }
效果如下图所示:
然后,在js文件里完成页面需要的点击事件。注意,这里的录音管理器是RecorderManager。

onLoad: function (options) {
var that = this; //获取全局唯一的录音管理器 RecorderManager实例 that.recorderManager = wx.getRecorderManager() that.recorderManager.onStop((res) => {
that.setData({
tempFilePath: res.tempFilePath // 文件临时路径 }) console.log('获取到文件:' + that.data.tempFilePath) }) this.recorderManager.onError((res) => {
console.log('录音失败了!') //console.log(res) }) },
开始录音的事件可以设置一些参数,如:采样率、录音通道数、音频格式等。
讯享网 //开始录音 start: function () {
this.recorderManager.start({
duration: 60000, sampleRate: 16000, //采样率,有效值 8000/16000/44100 numberOfChannels: 1, //录音通道数,有效值 1/2 encodeBitRate: 96000, //编码码率 format: 'mp3', //音频格式,有效值 aac/mp3 frameSize: 50, //指定帧大小 audioSource: 'auto' //指定录音的音频输入源,可通过 wx.getAvailableAudioSources() 获取 }) },
录音暂停、继续录音、录音停止事件只需要调用微信小程序的API即可。
//录音暂停 suspend: function () {
this.recorderManager.pause() }, //继续录音 continue: function () {
this.recorderManager.resume() }, //录音停止 stop: function () {
this.recorderManager.stop() },
播放录音事件需要先获取 innerAudioContext 实例,然后设置音频文件的路径,调用 onPlay() 方法即可播放。
讯享网 //播放录音 play: function () {
// 获取innerAudioContext实例 const innerAudioContext = wx.createInnerAudioContext() // 是否自动播放 innerAudioContext.autoplay = true // 设置音频文件的路径 innerAudioContext.src = this.data.tempFilePath; // 播放音频文件 innerAudioContext.onPlay(() => {
console.log('开始播放') }); // 监听音频播放错误事件 innerAudioContext.onError((res) => {
console.log(res.errMsg) console.log(res.errCode) }) } })
注意事项
之前播放音频使用的微信小程序接口是 wx.playVoice(Object object) ,但是从基础库 1.6.0 开始,该接口停止维护,所以我们使用 wx.createInnerAudioContext 代替。

完整项目代码获取:》》传送门《《

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/93068.html