ArticleZip > Html5 Record Audio To File

Html5 Record Audio To File

HTML5 has empowered developers with a wide range of capabilities, and one of the exciting features it offers is the ability to record audio directly to a file. In this article, we will walk you through the process of recording audio using HTML5 and saving it as a file on the user's device. This functionality opens up a world of possibilities, from creating voice memos to developing applications that require audio recording.

To get started, you will need a basic understanding of HTML, JavaScript, and HTML5's Audio API. The first step is to create an HTML file with an audio input element that will be used for recording. You can add this element to your page using the following code snippet:

Html

<audio controls id="audioRecorder"></audio>
<button id="recordButton">Record</button>
<button id="stopButton">Stop</button>

Next, you need to write the JavaScript code that will handle the recording process. You can achieve this by utilizing the MediaRecorder API provided by modern browsers. This API allows you to capture media streams, including audio, and save them as files. Here's a simple example of how you can implement audio recording in your HTML file:

Javascript

const audioRecorder = document.getElementById('audioRecorder');
const recordButton = document.getElementById('recordButton');
const stopButton = document.getElementById('stopButton');
let chunks = [];

recordButton.addEventListener('click', () =&gt; {
  navigator.mediaDevices.getUserMedia({ audio: true })
    .then((stream) =&gt; {
      const mediaRecorder = new MediaRecorder(stream);
      mediaRecorder.ondataavailable = (event) =&gt; {
        chunks.push(event.data);
      };

      mediaRecorder.onstop = () =&gt; {
        const blob = new Blob(chunks, { type: 'audio/wav' });
        const url = URL.createObjectURL(blob);
        audioRecorder.src = url;
      };

      mediaRecorder.start();
    })
    .catch((error) =&gt; {
      console.error('Error capturing audio: ', error);
    });
});

stopButton.addEventListener('click', () =&gt; {
  mediaRecorder.stop();
});

In the JavaScript code above, we first select the audio element and the record and stop buttons from the HTML document. We then set up event listeners for the record and stop buttons. When the record button is clicked, the code requests access to the user's audio input, initializes the MediaRecorder, and starts capturing audio data. The captured audio data is stored in chunks, and when the stop button is clicked, the data is combined into a single Blob and displayed in the audio element for playback.