PC端录音上传功能实现
- 前言
-
- 1.安装
- 2.调用
- 2.具体实现
- 总结
前言
最近项目中遇到一个需求:PC端实现录音生成文件并上传至服务器。js-audio-recorder 是一款比较好用的web端录制音频的js插件。接下来笔者将自己基于此插件实现该需求的具体过程分享出来,欢迎评论交流。
提示:
1.安装
npm i js-audio-recorder
2.调用
import Recorder from 'js-audio-recorder'
let recorder = new Recorder()
2.具体实现
代码如下(示例):
......
<el-button type="primary" @click="startRecord">开始</el-button>
<el-button type="primary" @click="pauseRecord">暂停</el-button>
<el-button type="primary" @click="resumeRecord">恢复</el-button>
<el-button type="primary" @click="destroyRecord">取消</el-button>
<el-button type="primary" @click="endRecord">结束</el-button>
<el-button type="primary" @click="playRecord">播放</el-button>
<el-button type="primary" @click="downloadPCM">下载pcm</el-button>
<el-button type="primary" @click="downloadWAV">下载wav</el-button>
<el-button type="primary" @click="upload">上传</el-button>
<h2>录音时长:{{duration}}s</h2>
......
data () {
return {
......
duration: '0',
recorder: null,
......
}
},
methods: {
// 是否支持录音
canTalk() {
return (
window.location.protocol.indexOf('https') === 0 ||
window.location.hostname === 'localhost' ||
window.location.hostname === '127.0.0.1'
)
},
// 开始录音
startRecord() {
if (!this.canTalk()) {
this.$message({
type: 'error',
message:
'由于浏览器安全策略, 非 HTTPS 或 非 localhost 访问, 录音功能不可用!',
duration: 5000
})
return
}
if(!this.recorder) {
this.recorder = new Recorder({
// 以下是默认配置
sampleBits: 16,
sampleRate: 16000, // 浏览器默认的输入采样率,
numChannels: 1,
})
this.recorder.onprocess = duration => {
this.duration = duration.toFixed(2)
}
this.recorder.start().then(() => {
console.log('开始录音')
}).catch(err => {
this.$alert('请插入麦克风!', '提示', {
confirmButtonText: '确定',
type: 'warning',
callback: action => {
this.recorder = null
}
})
return
})
}
},
// 暂停录音
pauseRecord() {
this.recorder && this.recorder.pause()
console.log('暂停录音')
},
// 恢复录音
resumeRecord() {
this.recorder && this.recorder.resume()
console.log('恢复录音')
},
// 结束录音
endRecord() {
this.recorder && this.recorder.stop()
console.log('结束录音')
},
// 取消录音
destroyRecord() {
this.recorder && this.recorder.destroy().then(() => {
this.duration = '0'
this.recorder = null
console.log('录音实例被销毁')
})
},
// 播放录音
playRecord() {
this.recorder && this.recorder.play()
},
// 下载pcm录音文件
downloadPCM() {
this.recorder && this.recorder.downloadPCM()
},
// 下载wav录音文件
downloadWAV() {
this.recorder && this.recorder.downloadWAV()
},
// 上传wav格式录音文件
upload() {
if(this.recorder) {
let blob = this.recorder.getWAVBlob()
let formData = new FormData()
formData.append('file', blob)
this.$axios.post('http://127.0.0.1:8090/admin/dish/image', formData).then(res => {
if(res.status === 200) {
this.$message.success('上传录音文件成功!')
} else {
this.$message.error('上传录音文件失败!')
}
})
}
}
总结
以上就是笔者基于js-audio-recorder实现PC端录音并上传录音文件的详细过程,欢迎大家评论交流!