Vivekanand Mogali
Vivekanand Mogali

Reputation: 41

How to mute microphone in javascript

So I am creating a video calling web app and I want to put mic on/off, video on/off functions in there.

navigator.mediaDevices.getUserMedia({
            video: true,
            audio: true
            }).then(stream => {
            const video= document.getElementById("my-video");
            video.srcObject = stream
            video.addEventListener('loadedmetadata', () => {
                video.play()
             })

It looks like this. Now I want to create a toggle function for my camera and micrphone. How do I do it

Upvotes: 3

Views: 5611

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20626

You receive a MediaStream using getUserMedia(). Stream consists of several tracks both video and audio.

videoMediaStream.getAudioTracks() will give you list of audio tracks.

videoMediaStream.getAudioTracks()[0].enabled = false will mute your mic.

This is what the docs mention regarding enabled property:

If the MediaStreamTrack represents the video input from a camera, disabling the track by setting enabled to false also updates device activity indicators to show that the camera is not currently recording or streaming. For example, the green "in use" light next to the camera in iMac and MacBook computers turns off while the track is muted in this way.

You can follow something similar for your camera using getVideoTracks().

Upvotes: 7

Related Questions