Record microphone audio on webpage


The article goes over how to stream and record microphone audio using HTML5 and JavaScript.

HTML

Add <audio> with controls and record/stop buttons:

<audio controls></audio>
<button id="record">Record</button>
<button id="stop">Stop</button>

JavaScript

Get the microphone audio using MediaDevices.getUserMedia():

var constraints = { audio: true };
navigator.mediaDevices.getUserMedia(constraints);

Record the microphone audio with MediaRecorder:

navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
  var mediaRecorder = new MediaRecorder(stream);
  var chunks = [];
  mediaRecorder.addEventListener('dataavailable', function (event) {
    chunks.push(event.data);
  });
});

When data is available, store the chunks:

navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
  // ...
  var chunks = [];
  mediaRecorder.addEventListener('dataavailable', function (event) {
    chunks.push(event.data);
  });
});

When the media recorder is stopped, convert the chunks to a Blob and set it on <audio>:

navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
  // ...
  var audio = document.querySelector('audio');
  mediaRecorder.addEventListener('stop', function () {
    var blob = new Blob(chunks, { type: 'audio/ogg; codecs=opus' });
    var url = URL.createObjectURL(blob);
    audio.src = url;
    chunks = []; // reset
  });
});

When the record button is clicked, start recording:

// ...
document.getElementById('record').addEventListener('click', function () {
  mediaRecorder.start();
});

When the stop button is clicked, stop recording:

// ...
document.getElementById('stop').addEventListener('click', function () {
  mediaRecorder.stop();
});

Code

Full example:

<!-- index.html -->
<audio controls></audio>
<button id="record">Record</button>
<button id="stop">Stop</button>
<script>
  var audio = document.querySelector('audio');
  var constraints = { audio: true };

  navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
    var mediaRecorder = new MediaRecorder(stream);
    var chunks = [];

    mediaRecorder.addEventListener('dataavailable', function (event) {
      chunks.push(event.data);
    });

    mediaRecorder.addEventListener('stop', function () {
      var blob = new Blob(chunks, { type: 'audio/ogg; codecs=opus' });
      var url = URL.createObjectURL(blob);
      audio.src = url;
      chunks = []; // reset
    });

    document.getElementById('record').addEventListener('click', function () {
      mediaRecorder.start();
    });

    document.getElementById('stop').addEventListener('click', function () {
      mediaRecorder.stop();
    });
  });
</script>

Demo

Replit:

You will get Permission denied when running the Replit in an <iframe>. You can check out the demo webpage instead:

Resources



Please support this site and join our Discord!