audio.html 1.83 KB
Newer Older
Ford committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
<!DOCTYPE html>
<html>
<head>
    <title>录制音频示例</title>
</head>
<body>
<button id="startRecord">开始录音</button>
<button id="stopRecord" disabled>停止录音</button>
<audio id="audioPlayback" controls></audio>

<script>
    let mediaRecorder;
    let audioChunks = [];

    // 开始录音按钮点击事件
    document.getElementById('startRecord').addEventListener('click', () => {
        navigator.mediaDevices.getUserMedia({ audio: true })
            .then(stream => {
                mediaRecorder = new MediaRecorder(stream);
                mediaRecorder.ondataavailable = e => {
                    audioChunks.push(e.data);
                };
                mediaRecorder.onstop = e => {
                    const audioBlob = new Blob(audioChunks);
                    const audioUrl = URL.createObjectURL(audioBlob);
                    const audio = document.getElementById('audioPlayback');
                    audio.src = audioUrl;
                    // 以下代码用于下载录音文件
                    const a = document.createElement('a');
                    a.href = audioUrl;
                    a.download = 'recording.wav';
                    a.click();
                    window.URL.revokeObjectURL(audioUrl);
                };
                mediaRecorder.start();
                document.getElementById('startRecord').disabled = true;
                document.getElementById('stopRecord').disabled = false;
                audioChunks = [];
            })
            .catch(e => console.error(e));
    });

    // 停止录音按钮点击事件
    document.getElementById('stopRecord').addEventListener('click', () => {
        mediaRecorder.stop();
        document.getElementById('startRecord').disabled = false;
        document.getElementById('stopRecord').disabled = true;
    });
</script>
</body>
</html>