微信小程序实现语音录制(uni-app源码版)
注意以下代码只是部分代码,已经将完整代码上传至插件市场,可在插件市场中下载。
插件下载地址
1. 创建音频对象上下文
// 创建音频上下文
let innerAudioContext = uni.createInnerAudioContext({
useWebAudioImplement: false,
})
this.innerAudioContext = innerAudioContext
// 创建录音全局唯一对象
let recorderManager = uni.getRecorderManager()
this.recorderManager = recorderManager
// 监听录音结束
recorderManager.onStop((e) => {
let duration = (e.duration / 1000).toFixed(1)
this.voice = {
src: e.tempFilePath,
duration: duration,
}
this.$emit('success', this.voice)
})
2. 点击开始录音方法
/**
* 开始录音
*/
start() {
let recorderManager = this.recorderManager
uni.vibrateShort({
success: (e) => {
if (!this.isClick) {
this.interval = setInterval(() => {
this.duration = this.duration + 0.1
}, 100)
recorderManager.start()
this.isActive = true
}
},
})
}
3. 点击结束录音方法
/**
* 结束录音
*/
end() {
let recorderManager = this.recorderManager
recorderManager.stop()
this.isActive = false
if (this.interval) {
clearInterval(this.interval)
this.interval = null
this.duration = 0
}
setTimeout(() => {
this.isClick = false
}, 200)
},
4. 播放录音方法
play() {
if (this.voice) {
this.innerAudioContext.src = this.voice.src
this.innerAudioContext.play()
}
},