Getting Browser Microphone Permission

After you’ve created the peer, you’ll want to get the browser’s permission to access the microphone. We’ll be using the getUserMedia function on the navigator.MediaDevices object, which is part of the Media Devices Web interface. The getUserMedia endpoint takes a constraints object which specifies which permissions are needed. getUserMedia is a promise which when successfully resolved returns a MediaStream object. In this case this is going to be the audio from our stream. If the promise isn’t successfully resolved, you’ll want to catch and display the error.

function getLocalStream() {
    navigator.mediaDevices.getUserMedia({video: false, audio: true}).then( stream => {
        window.localStream = stream; // A
        window.localAudio.srcObject = stream; // B
        window.localAudio.autoplay = true; // C
    }).catch( err => {
        console.log("u got an error:" + err)
    });
}

A. window.localStream = stream : here we’re attaching the MediaStream object (which we have assigned to stream on the previous line) to the window as the localStream .

B. window.localAudio.srcObject = stream: in our HTML, we have an audio element with the ID localAudio, we’re setting that element’s src attribute to be the MediaStream returned by the promise.

C. window.localAudio.autoplay = true: we’re setting the autoplay attribute for the audio element to auto play.

If you’ve done some sleuthing online, you may have come across navigator.getUserMedia and assumed you can use that instead of navigator.MediaDevices.getUserMedia. You’d be wrong. The former is a deprecated method which requires callbacks as well as constraints as arguments. The latter uses a promise so you don’t need to use callbacks.

When you call your getLocalStream function and refresh your browser, you should see the following permission pop up:

A browser permission dialogue box which says "http://localhost:8000 wants to use your microphone" with two options: "block" and "allow"

Use headphones before you allow so that when you unmute yourself later, you don’t get any feedback. If you don’t see this, open the inspector and see if you have any errors. Make sure your javascript file is correctly linked to your index.html too.

This what it should all look like together:

/* global Peer */

/**
 * Gets the local audio stream of the current caller
 * @param callbacks - an object to set the success/error behavior
 * @returns {void}
 */

function getLocalStream() {
    navigator.mediaDevices.getUserMedia({video: false, audio: true}).then( stream => {
        window.localStream = stream;
        window.localAudio.srcObject = stream;
        window.localAudio.autoplay = true;
    }).catch( err => {
        console.log("u got an error:" + err)
    });
}

getLocalStream();