最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set volumes in WebRTC? - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Apr 29, 2017 at 18:12 Maria Ines Parnisari 17.5k10 gold badges93 silver badges138 bronze badges asked Apr 29, 2017 at 18:09 이영우이영우 671 gold badge1 silver badge5 bronze badges 1
  • Related: stackoverflow./questions/16942773/… – Maria Ines Parnisari Commented Apr 29, 2017 at 18:12
Add a ment  | 

1 Answer 1

Reset to default 12

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);
    windowinalStream = 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

发布评论

评论列表(0)

  1. 暂无评论