在前端使用JS生成音频文件并保存到本地
背景
笔者在前端开发过程中,有时会遇到需要音频文件用来测试语音播放的场景,而在网上下载的文件大小、格式可能不符合要求。于是思考如何在前端直接生成一个 audio/webm 格式的文件,并保存到本地?
思路
我们使用浏览器自带的 MediaRecorder API 来实现这个需求。
- 首先需要录制一些音频数据。先请求访问用户的麦克风,然后开始录制音频,当录制停止时,它将所有的音频块组合成一个 Blob 对象,其类型为 audio/webm;
- 然后我们需要将这个 Blob 保存到本地。我们可以创建一个链接元素,并使用 URL.createObjectURL() 来生成一个指向这个 Blob 的 URL,然后触发下载:
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>录音并保存为WebM</title>
</head>
<body><h1>录音并保存为WebM</h1><button id="start">开始录音</button><button id="stop" disabled>停止录音</button><script>let mediaRecorder;let audioChunks = [];async function startRecording() {try {const stream = await navigator.mediaDevices.getUserMedia({ audio: true });mediaRecorder = new MediaRecorder(stream);mediaRecorder.ondataavailable = event => {audioChunks.push(event.data);};mediaRecorder.onstop = () => {const audioBlob = new Blob(audioChunks, { type: 'audio/webm' });console.log('audioBlob',audioBlob)saveAudioToFile(audioBlob);audioChunks = [];};mediaRecorder.start();} catch (err) {console.error("无法访问麦克风", err);}}function stopRecording() {if(mediaRecorder){mediaRecorder.stop();}}function saveAudioToFile(blob) {const url = URL.createObjectURL(blob);const a = document.createElement('a');a.style.display = 'none';a.href = url;a.download = 'recording.webm'; // 设置下载文件的名字和扩展名,可自由定义document.body.appendChild(a);a.click();window.URL.revokeObjectURL(url);document.body.removeChild(a); // 清理创建的a标签}document.getElementById('start').onclick = () => {startRecording();document.getElementById('start').disabled = true;document.getElementById('stop').disabled = false;};document.getElementById('stop').onclick = () => {stopRecording();document.getElementById('start').disabled = false;document.getElementById('stop').disabled = true;};</script>
</body>
</html>