开始录制
startRecording() {
navigator.mediaDevices
.getUserMedia({ audio: true })
.then(stream => {
this.isRecording = true // 开始录制
this.mediaRecorder = new MediaRecorder(stream)
// 如果要监听语音,需要在mediaRecorder.start定义监听时间间隔,否则不会生效
this.mediaRecorder.addEventListener('dataavailable', this.handleDataAvailable)
this.mediaRecorder.start(1000) // 1000s返回一次有效语音
})
.catch(error => {
console.error('当前浏览器无法访问麦克风', error)
})
}
监听到有效语音的处理方法
// 处理可用的数据
async handleDataAvailable(event) {
this.chunksRecorder.push(event.data)
await this.processRecordedAudio()
}
async processRecordedAudio() {
const blob = new Blob(this.chunksRecorder, { type: 'audio/mpeg' }) // mp3
let text = await this.getTextByAudio(blob) // 后端的语音转文字功能
if (text) {
this.inputValue = text
}
}
后端的语音转文字功能
async getTextByAudio(file) {
const formData = new FormData()
formData.append('files', file) // 将文件添加到 FormData 中
formData.append('lang', 'zh') // 将文件添加到 FormData 中
// 后端语音转文字
let response = await axios.post(
'',
formData,
{
headers: {
'Content-Type': 'application/json', // 设置请求头
},
},
)
return response.data?.result?.text || ''
}
结束录制
async stopRecording() {
this.isRecording = false
this.chunksRecorder=[]
// 移除监听
this.mediaRecorder.removeEventListener('dataavailable', this.handleDataAvailable)
this.mediaRecorder.stop()
this.mediaRecorder.stream.getTracks().forEach(track => track.stop()) // 释放资源
this.mediaRecorder = null
}
如果需要下载录音
save() {
const blob = new Blob(this.chunksRecorder, { type: 'audio/mpeg' });
const audioURL = window.URL.createObjectURL(blob);
const fileName = Date.now().toString(32);
const fileType = "audio/mpeg";
const file = new window.File([blob], fileName, { type: fileType });
// 下载
const a = document.createElement("a");
a.href = audioURL;
a.download = fileName;
a.click();
}