Explain Codes LogoExplain Codes Logo

Html5 record audio to file

html
audio-export
javascript-promises
user-consent
Anton ShumikhinbyAnton Shumikhin·Nov 15, 2024
TLDR

Rapidly record audio using HTML5 with the getUserMedia() API from MediaDevices to access a microphone and the MediaRecorder API to capture the audio. Consolidate the audio data into a Blob for user download.

Here's your main dish (the code snippet):

navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => { const mediaRecorder = new MediaRecorder(stream); // The DJ, handling the fidelity of your audio let audioChunks = []; mediaRecorder.ondataavailable = e => audioChunks.push(e.data); // Collect the sound bites mediaRecorder.onstop = () => { const audioBlob = new Blob(audioChunks); // Merge all those sweet sound bites into one digestible Blob const audioUrl = URL.createObjectURL(audioBlob); const link = document.createElement('a'); // This link is our audio cassette ribbon, hold it sacred link.href = audioUrl; // Attach the ribbon to the cassette link.download = 'recording.webm'; // Your audio file, created by the secret powers of JavaScript document.body.appendChild(link); link.click(); document.body.removeChild(link); }; mediaRecorder.start(); setTimeout(() => mediaRecorder.stop(), 3000); // After 3 sec, stop() breaks the recording party }).catch(console.error); // Handling errors with style

Focus on user consent and error handling to complete the user experience.

Audio export and download demystified

To export the audio into a .wav file, you should use the revered exportWAV method.

recorder.exportWAV(blob => { // Do magic with the Blob object, transport it to a server, create a vinyl out of it, your choice really });

Or, make your file ready for an immediate download with the venerable forceDownload method, as explained below:

recorder.exportWAV(blob => { Recorder.forceDownload(blob, 'filename.wav'); // Your file, served hot and instantly });

The JavaScript in the AudioRecorder demo will hold your hand through creating the stream that gets attached to the <audio> element.

Why need a wizard when MediaRecorder does it for you

MediaRecorder.ondataavailable event interacts with your audio data. start() and stop() methods give you fine-grained control. See, no magic wand required:

mediaRecorder.ondataavailable = e => { // Process your audio data like a pro here }; mediaRecorder.start(); // The starting gong at your recording session // Record audio before your coffee gets cold, or just as long as you want mediaRecorder.stop(); // End scene, stop the recording, have your coffee

For those who like it simple, say hi to JSSoundRecorder. A modern-day music hero, it enables you to record, edit, and download audio seamlessly. For all the juicy details and implementation, check out its GitHub repository.

Planning ahead: Error handling and licensing

Ensure a smooth recording experience with onRecordFail for robust error handling:

function onRecordFail() { console.error('Oops! Recording failed - user denied microphone access.'); // If only we had the "chicken will cross the road" joke for such sad cases } navigator.getUserMedia({audio: true}, stream => { // The stream, your golden ticket to the microphone }, onRecordFail);

Remember, some recorders, like the mp3 gang, may have licensing issues. So, turn to our friend, MIT license, when reusing code.

Choosing the right format: WAV, MP3, or Ogg

Choosing the right recording format is like choosing the right attire for a party. The .wav format offers uncompressed audio, great for a high-quality soirée, but beware the large file size. For a compressed format, with good quality at a smaller file size, the .ogg format might be your go-to casual wear.

To adjust your code for specific requirements, such as local saving or uploading to a server, you need to tweak the HTML5 code. And yes, user interaction, like playback controls and managing multiple recorded files should also be on your checklist.

User trust is key, get their consent before accessing the microphone:

navigator.mediaDevices.getUserMedia({audio: true}) .then(stream => { // You can hear the birds chirping, the user has granted access to the microphone }) .catch(error => { console.error('Access denied by user', error); // Looks like someone shut the windows on you });

Integrate simple visual or audio feedback during recording to keep users in the loop. A flashing red light or a sound wave visualization would do the trick.