To record audio to a file using JavaScript, you can utilize the Web Audio API along with the MediaStream Recording API.
For example, we write:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audio Recorder</title>
</head>
<body>
<button id="startRecording">Start Recording</button>
<button id="stopRecording" disabled>Stop Recording</button>
<audio controls></audio>
<script>
// Accessing user's microphone
navigator.mediaDevices.getUserMedia({ audio: true })
.then(function(stream) {
const audioContext = new AudioContext();
const mediaStreamSource = audioContext.createMediaStreamSource(stream);
const recorder = new MediaRecorder(stream);
const chunks = [];
recorder.ondataavailable = function(event) {
chunks.push(event.data);
};
recorder.onstop = function(event) {
const blob = new Blob(chunks, { type: 'audio/ogg; codecs=opus' });
const audioURL = window.URL.createObjectURL(blob);
const audioElement = document.querySelector('audio');
audioElement.src = audioURL;
};
document.getElementById('startRecording').addEventListener('click', function() {
recorder.start();
this.disabled = true;
document.getElementById('stopRecording').disabled = false;
});
document.getElementById('stopRecording').addEventListener('click', function() {
recorder.stop();
this.disabled = true;
document.getElementById('startRecording').disabled = false;
});
})
.catch(function(err) {
console.error('Error accessing microphone:', err);
});
</script>
</body>
</html>
This example sets up a basic HTML page with two buttons (“Start Recording” and “Stop Recording”) and an <audio>
element.
When the “Start Recording” button is clicked, it requests access to the user’s microphone.
Once access is granted, it creates an AudioContext
and a MediaStreamSource
from the microphone stream. It then sets up a MediaRecorder
instance to record the audio chunks and pushes them into an array.
When the “Stop Recording” button is clicked, it stops the recording and assembles the recorded chunks into a single audio blob.
Finally, it creates a URL for the audio blob and sets it as the source for the <audio>
element, allowing playback of the recorded audio.