使用音量增益时如何正确释放audioContext

How to properly release audioContext when using volume gain

使用WebRTC时,停止直播后,网络摄像头灯会熄灭,chrome选项卡上的"red dot"也会消失。 (如下图所示)

vid = document.createElement('VIDEO');
vid.style.width = 100;
vid.style.height = 100;
vid.style.top = 100;
vid.style.left = 0;
vid.style.position = 'absolute';
vid.style.border = '1px solid red';
vid.id = 'xxx';
document.body.insertBefore(vid,document.body.childNodes[0]);
xxx = document.getElementById('xxx');
var xstream = null;

navigator.webkitGetUserMedia({video:true, audio:true},
  function(stream) {
    xstream = stream;    
    xxx.src = window.URL.createObjectURL(stream);
  },
  function(error) {
    console.log('err', error);
  }
);
xxx.play();

所以当我执行以下操作时:

xstream.stop();

我准备好了,网络摄像头灯熄灭,选项卡上的红点立即消失。

但是当我像下面这样使用 "audioContext" 时:

vid = document.createElement('VIDEO');
vid.style.width = 100;
vid.style.height = 100;
vid.style.top = 100;
vid.style.left = 0;
vid.style.position = 'absolute';
vid.style.border = '1px solid red';
vid.id = 'xxx';
document.body.insertBefore(vid,document.body.childNodes[0]);
xxx = document.getElementById('xxx');
var xstream = null
    wp = {};

navigator.webkitGetUserMedia({video:true, audio:true},
  function(stream) {
    xstream = stream;

    wp.audio = {
        source: null,
        volume: null,
        enabled: true
    }
    wp.audioContext = new window.AudioContext();
    wp.audio.source = wp.audioContext.createMediaStreamSource(stream);
    wp.audio.volume = wp.audioContext.createGain();
    wp.audio.destination = wp.audioContext.createMediaStreamDestination();
    wp.audio.outputStream = wp.audio.destination.stream;
    wp.audio.source.connect(wp.audio.volume);
    wp.audio.volume.connect(wp.audio.destination);
    stream.addTrack(wp.audio.outputStream.getAudioTracks()[0]);
    stream.removeTrack(stream.getAudioTracks()[0]);

    xxx.src = window.URL.createObjectURL(stream);
  },
  function(error) {
    console.log('err', error);
  }
);
xxx.play();

如果我简单的做一个xstream.stop(),虽然摄像头灯灭了,但是红点还在。

但是如果我执行以下操作:

wp.audio.source.mediaStream.stop();
wp.audio.destination.stream.stop();
wp.audio.outputStream.stop();
wp.audio.source.disconnect();
wp.audio.volume.disconnect();
wp.audio.destination = null;
wp.audio.source = null;
wp.audio.volume = null;
wp.audio.outputStream = null;
wp.audioContext.close();
xstream.stop();
xxx.src = '';

有时红点会消失,大多数时候不会。当它消失时,通常需要 20 - 40 秒,有时甚至更长。

不确定我在这里做错了什么。

注意:您可以在控制台中复制并粘贴代码进行试用

也许你可以尝试在 stream.removeTrack

之前停止直播