微信小程序实现录音及本地录音播放功能
项目需求在做一个项目时需要有这样的功能:用户可以通过微信小程序录音且录音完成后可以播放自己的录音。项目实施首先,在前端界面上绘制几个按钮,分别添加上点击事件。index.wxml<!--index.wxml--><view class="container"><button type="primary" bindtap="start">开始录音</butt
·
项目需求
在做一个项目时需要有这样的功能:用户可以通过微信小程序录音且录音完成后可以播放自己的录音。
项目实施
首先,在前端界面上绘制几个按钮,分别添加上点击事件。
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 代替。
完整项目代码获取:》》传送门《《
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
已为社区贡献1条内容
所有评论(0)