vue实现录音
Vue 实现录音功能
在 Vue 中实现录音功能通常需要结合浏览器提供的 Web Audio API 或第三方库。以下是两种常见的方法:
使用 Web Audio API
Web Audio API 是浏览器原生提供的音频处理接口,可以直接在 Vue 项目中使用。
// 在 Vue 组件中
methods: {
startRecording() {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
this.mediaRecorder = new MediaRecorder(stream)
this.chunks = []
this.mediaRecorder.ondataavailable = e => {
this.chunks.push(e.data)
}
this.mediaRecorder.onstop = () => {
const blob = new Blob(this.chunks, { type: 'audio/wav' })
this.audioUrl = URL.createObjectURL(blob)
}
this.mediaRecorder.start()
})
.catch(err => {
console.error('Error accessing microphone:', err)
})
},
stopRecording() {
if (this.mediaRecorder) {
this.mediaRecorder.stop()
this.mediaRecorder.stream.getTracks().forEach(track => track.stop())
}
}
}
使用第三方库 recorder-js
recorder-js 是一个轻量级的录音库,可以简化录音实现过程。
安装依赖:
npm install recorder-js
组件实现:

import Recorder from 'recorder-js'
export default {
data() {
return {
recorder: null,
audioBlob: null,
audioUrl: null
}
},
methods: {
async startRecording() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
this.recorder = new Recorder(stream)
this.recorder.start()
} catch (err) {
console.error('Recording error:', err)
}
},
stopRecording() {
if (this.recorder) {
this.recorder.stop()
.then(({ blob }) => {
this.audioBlob = blob
this.audioUrl = URL.createObjectURL(blob)
})
}
}
}
}
注意事项
-
确保在 HTTPS 环境下或 localhost 开发环境中使用,大多数浏览器要求安全上下文才能访问麦克风
-
添加适当的用户界面提示,告知用户需要麦克风权限
-
考虑添加录音时长限制,防止过长的录音占用过多内存

-
移动端兼容性需要额外测试,不同设备可能有不同的行为
-
录音格式转换可能需要额外处理,如需要 MP3 格式可使用 lamejs 等库
扩展功能
实现录音可视化可以结合 Web Audio API 的 AnalyserNode:
setupVisualizer(audioContext) {
const analyser = audioContext.createAnalyser()
analyser.fftSize = 256
const bufferLength = analyser.frequencyBinCount
const dataArray = new Uint8Array(bufferLength)
// 使用 requestAnimationFrame 持续获取和分析音频数据
// 可用于绘制波形或频谱图
}
以上方法提供了在 Vue 中实现录音功能的基本框架,可根据具体需求进行调整和扩展。






