1

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 Answers1

0

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

NickG
  • 550
  • 4
  • 18
  • Hey NickG. Thanks for the comment. I implemented the mute/unmute-ing part by changing property 'enabled' on an audioTrack. Do you know how can I controll the volume of the output ? That's the main thing I am trying to find out – Nika Khachiashvili Mar 12 '22 at 16:10
  • You can adjust the volume by using AudioContext and a gainNode. In this thread is an example on how to use it: https://stackoverflow.com/a/43702567/8788847. Just use the destination stream as input for your MediaRecorder. – NickG Mar 13 '22 at 19:26
  • Will try. Thanks – Nika Khachiashvili Mar 14 '22 at 07:15