js网页实现录音
使用 Web Audio API 和 MediaRecorder
在网页中实现录音功能可以通过 Web Audio API 和 MediaRecorder API 实现。以下是一个完整的实现方案:
// 获取用户麦克风权限
navigator.mediaDevices.getUserMedia({ audio: true })
.then(function(stream) {
// 创建音频上下文
const audioContext = new AudioContext();
const mediaStreamSource = audioContext.createMediaStreamSource(stream);
// 创建MediaRecorder实例
const mediaRecorder = new MediaRecorder(stream);
let audioChunks = [];
// 开始录制
document.getElementById('startBtn').addEventListener('click', () => {
audioChunks = [];
mediaRecorder.start();
});
// 停止录制
document.getElementById('stopBtn').addEventListener('click', () => {
mediaRecorder.stop();
});
// 收集音频数据
mediaRecorder.ondataavailable = function(e) {
audioChunks.push(e.data);
};
// 录制完成处理
mediaRecorder.onstop = function() {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
// 播放录音
document.getElementById('playBtn').addEventListener('click', () => {
audio.play();
});
// 下载录音
document.getElementById('downloadBtn').addEventListener('click', () => {
const a = document.createElement('a');
a.href = audioUrl;
a.download = 'recording.wav';
a.click();
});
};
})
.catch(function(err) {
console.error('获取麦克风权限失败:', err);
});
添加HTML界面
<button id="startBtn">开始录音</button>
<button id="stopBtn">停止录音</button>
<button id="playBtn">播放录音</button>
<button id="downloadBtn">下载录音</button>
处理兼容性问题
不同浏览器对音频格式的支持可能不同。可以通过检查MediaRecorder的isTypeSupported方法来确保兼容性:
if (MediaRecorder.isTypeSupported('audio/webm')) {
options = { mimeType: 'audio/webm' };
} else if (MediaRecorder.isTypeSupported('audio/ogg')) {
options = { mimeType: 'audio/ogg; codecs=opus' };
} else {
options = { mimeType: 'audio/wav' };
}
const mediaRecorder = new MediaRecorder(stream, options);
错误处理
添加适当的错误处理可以提高用户体验:
navigator.mediaDevices.getUserMedia({ audio: true })
.catch(err => {
alert('无法访问麦克风,请检查权限设置');
console.error('麦克风访问错误:', err);
});
音频可视化
可以使用AnalyserNode实现录音时的音频可视化效果:

const analyser = audioContext.createAnalyser();
mediaStreamSource.connect(analyser);
function drawWaveform() {
const bufferLength = analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
analyser.getByteTimeDomainData(dataArray);
// 使用canvas绘制波形
const canvas = document.getElementById('waveform');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
for(let i = 0; i < bufferLength; i++) {
const x = i * canvas.width / bufferLength;
const y = dataArray[i] / 255 * canvas.height;
if(i === 0) {
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
}
}
ctx.stroke();
requestAnimationFrame(drawWaveform);
}
drawWaveform();
注意事项
- 现代浏览器要求网页通过HTTPS协议或在localhost环境下才能访问麦克风
- 首次使用时浏览器会请求麦克风权限
- 录音功能在移动设备上可能有不同的行为
- 长时间录音需要考虑内存使用问题






