How to control microphone output from JavaScript?

1.1k Views Asked by At

I am building an app, which needs to record a microphone. I want users to control microphone output from the app, mute/unmute it.

Is it possible ? If yes, how can I achieve that ?

React version of the project

   "react": "^17.0.2",

Code where I get an microphono input

const handleRecord = async () => {
    setIsAudioLoading(true);
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    const mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/wav" });
    let orderNumber = 0;
    let chunks = [];

    mediaRecorder.ondataavailable = function (e) {
      chunks.push(e.data);
    };
    mediaRecorder.onstop = function () {
      const blob = new Blob(chunks, { type: "audio/wav" });
      streamChunk(blob, orderNumber, "mic");
      chunks = [];
    };

    mediaRecorder.start();

    setStopMic(() => () => {
      setIsMicPaused(true);
      setCurrentAudioTime(lastChunkSecondRef.current - 1.5);
      isMicPausedRef.current = true;
      mediaRecorder.stop();
    });
    setStartMic(() => () => {
      setIsMicPaused(false);
      isMicPausedRef.current = false;
      mediaRecorder.start();
    });

    setInterval(function () {
      if (!isMicPausedRef.current) {
        orderNumber++;
        mediaRecorder.stop();
        mediaRecorder.start();
      }
    }, MIC_INTERVAL);
  };

1

There are 1 best solutions below

3
NickG On

You can mute and unmute your recording by changing the stream track muted property like so:

let tracks = stream.getAudioTracks();

//muting
tracks.forEach(track => {
  track.muted = true;
});

//unmuting
tracks.forEach(track => {
  track.muted = false;
});

You can find more a detailed description of the muted property here:
https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack/muted

In case you need to track the muted property, you can listen to track.onmute and track.onunmute events. If you need to adjust the volume of your recording aswell, you should take a look into the Web Audio API: https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API