이영우
이영우

Reputation: 67

How to set volumes in WebRTC?

I want to know how to set the volume in WebRTC.

I'm drawing audio like this:

audio = document.createElement('audio');
audio.controls = true;
audio.autoplay = true;
audio.src = window.URL.createObjectURL(stream);
div.appendChild(audio);

I want to make my custom Audio UI. So, I will use HTML's slide bar.

<input type="range">

But, I don't know set volumes in WebRTC stream. How can I set it?

Upvotes: 5

Views: 14823

Answers (1)

Ajay
Ajay

Reputation: 2643

For output(speakers) audio volume, you can manage with volume property of audio/video element.

var audio = document.getElementById('audioId');
audio.volume = 0.9; // 0.0(Silent) -> 1 (Loudest)

You can change the audio.volume based on your slide bar position

To change input(microphone) volume, there is no direct method available in WebRTC AudioTrack/MediaStream.

We can use WebAudio Api to handle volume at Stream/Track level and you can connect WebAudio output to PeerConnection as following

var audioContext = new AudioContext()
var gainNode = audioContext.createGain(); 
navigator.mediaDevices.getUserMedia({audio:true})
.then((stream) => {
    console.log('got stream', stream);
    window.orginalStream = stream;
    return stream;
})
.then((stream) => {
    audioSource = audioContext.createMediaStreamSource(stream),
    audioDestination = audioContext.createMediaStreamDestination();
    audioSource.connect(gainNode);
    gainNode.connect(audioDestination);
    gainNode.gain.value = 1;
    window.localStream = audioDestination.stream;
    //audioElement.srcObject = window.localStream; //for playback
    //you can add this stream to pc object
    // pc.addStream(window.localStream);
})
.catch((err) => {
    console.error('Something wrong in capture stream', err);
})

Now we can easily control the microphone volume with below function

function changeMicrophoneLevel(value) {
    if(value && value >= 0 && value <= 2) {
        gainNode.gain.value = value;
    }
}

For more info have a look at my demo

Upvotes: 12

Related Questions