Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mikoloism/63148d3562d45ab524e868de19be18df to your computer and use it in GitHub Desktop.
Save mikoloism/63148d3562d45ab524e868de19be18df to your computer and use it in GitHub Desktop.
how record audio with javascript (html)

How record audio with javascript in browser(html)

Coding

HTML Elements

<div class="recorder__container">
  <button class="recorder__button recorder__button--record" id="recorder-record-button">Record</button>
  <button class="recorder__button recorder__button--paly" id="recorder-play-button">Play</button>
</div>

then import javascript file

insert below code on end of body

<script
        type="text/javascript"
        src="./audio-recorder.js"
        defer
        async>
</script>

Javascript

1. create recorder function

const record = () =>
  new Promise(async resolve => {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    const mediaRecorder = new MediaRecorder(stream);
    const audioChunks = []; // we store audio records in this array
    
    mediaRecorder.addEventListener("dataavailable", event => {
      audioChunks.push(event.data);
    });

    const start = () => mediaRecorder.start();
    const stop = () =>
      new Promise(resolve => {
        mediaRecorder.addEventListener("stop", () => {
          const audioBlob = new Blob(audioChunks);
          const audioUrl = URL.createObjectURL(audioBlob);
          const audio = new Audio(audioUrl);
          const play = () => audio.play();
          resolve({ audioBlob, audioUrl, play });
        });

        mediaRecorder.stop();
      });

    resolve({ start, stop });
  });

2. how to use

let recorder = null;
let audio = null;

const recordStop = async () => {
  if (recorder) {
    audio = await recorder.stop();
    recorder = null;
    document.querySelector("#recorder-record-button").textContent = "Record";
    document.querySelector("#recorder-play-button").removeAttribute("disabled");
  } else {
    recorder = await recordAudio();
    recorder.start();
    document.querySelector("#record-record-button").textContent = "Stop";
  }
};

const playAudio = () => {
  if (audio && typeof audio.play === "function") {
    audio.play();
  }
};

GMAIL | CODEPEN | GITHUB | ORIGINAL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment