我的意图是录制最长为 2 分钟的音频,但用户可以通过单击停止按钮提前停止录制。然后用户可以预览录制的音频。但是点击停止录制尝试预览后,出现错误
这是我的代码,我对每一行都做了注释,如果有人能告诉我我的代码有什么问题,我将不胜感激。谢谢!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Audio Recorder</title>
<script>
let chunks = []; // Array to store audio chunks
let mediaRecorder; // MediaRecorder object to record audio
let isRecording = false; // Boolean to track if recording is in progress
const MAX_RECORDING_TIME_MS = 120000; // Max recording time in milliseconds
// Function to handle button click
function handleRecordClick() {
if (!isRecording) {
startRecording();
} else {
stopRecording();
}
}
// Function to start recording
function startRecording() {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(function(stream) {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
isRecording = true;
// Change button text and color
const recordButton = document.getElementById("recordButton");
recordButton.textContent = "Stop Recording";
recordButton.classList.add("stop");
// Set timeout to stop recording after max recording time
setTimeout(stopRecording, MAX_RECORDING_TIME_MS);
})
.catch(function(err) {
console.log("Error starting recording:", err);
});
// Add event listener to mediaRecorder to store audio chunks
mediaRecorder.addEventListener("dataavailable", function(event) {
chunks.push(event.data);
});
}
// Function to stop recording
function stopRecording() {
if (isRecording) {
mediaRecorder.stop();
isRecording = false;
// Change button text and color
const recordButton = document.getElementById("recordButton");
recordButton.textContent = "Record";
recordButton.classList.remove("stop");
// Create audio object from recorded chunks
const blob = new Blob(chunks, { type: "audio/webm" });
const audioUrl = URL.createObjectURL(blob);
const audio = new Audio(audioUrl);
// Create preview player and append to page
const preview = document.createElement("audio");
preview.controls = true;
preview.src = audioUrl;
const previewContainer = document.getElementById("previewContainer");
previewContainer.innerHTML = ""; // Clear previous preview (if any)
previewContainer.appendChild(preview);
// Clear chunks array
chunks = [];
}
}
</script>
<style>
#recordButton {
font-size: 24px;
padding: 16px;
border-radius: 8px;
background-color: #008CBA;
color: #FFFFFF;
border: none;
cursor: pointer;
}
#recordButton.stop {
background-color: #f44336;
}
</style>
</head>
<body>
<h1>Audio Recorder</h1>
<button id="recordButton" onclick="handleRecordClick()">Record</button>
<div id="previewContainer"></div>
</body>
</html>