'Play realtime audio from mic to speaker in javascript

I need to capture audio from mic and play it realtime. How can I implement that in js? I don't want record, save and then play. I want the realtime output on my speaker.

const recordAudio = () =>
  new Promise(async resolve => {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    const mediaRecorder = new MediaRecorder(stream);
    const audioChunks = [];

    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 });
  });

const sleep = time => new Promise(resolve => setTimeout(resolve, time));

(async () => {
  const recorder = await recordAudio();
  recorder.start();
  await sleep(3000);
  const audio = await recorder.stop();
  audio.play();
})();


Solution 1:[1]

This is the working code after doing lot's of efforts.

  if (navigator.mediaDevices) {
    const constraints = window.constraints = {
      audio: true, 
      video: false
    }
    navigator.mediaDevices.getUserMedia(constraints)
    .then( stm => {
      handleSuccess(stm);
    }
    ).catch(handleError);
  }

function handleSuccess(stream) {
  if (window.stream) {
    window.stream.getAudioTracks().forEach(track => track.stop());
    window.stream = null;
  } else {
    const audio = document.createElement('audio');
    audio.controls = true;
    audio.autoplay = true;
    window.stream = stream;
    audio.srcObject = stream;

    stream.oninactive = function() {
      console.log('Stream ended');
    };
  }
}

function handleError(e){
  console.log("Alert", e.message);
  //alert('Error: ' + e.message);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Fuad Hasan