如何完全关闭音频输入流

how to fully shutdown audio input stream

我创建了一个执行音调检测的音频工作集,一切正常,但我想在完成后释放麦克风

我得到流并像这样连接所有东西

        const AudioContextConstructor =
            window.AudioContext || window.webkitAudioContext;
        this.audioContext = new AudioContextConstructor();

        await this.audioContext.audioWorklet.addModule('js/worklet_pitcher.js');
        this.stream = await navigator.mediaDevices.getUserMedia({ audio: true });

        var mediaStreamSource = this.audioContext.createMediaStreamSource(this.stream);
        this.pitchWorklet = new AudioWorkletNode(this.audioContext, 'pitch-processor');
        mediaStreamSource.connect(this.pitchWorklet);

完成后,我只需这样做

stop = (): void => {
     if (this.running) {
        this.audioContext.close();
        this.running = false;
    }
}

这会停止 Worklet 管道,但红点仍显示在浏览器选项卡中,这意味着我仍然拥有麦克风。

我寻找 stream.close 以便我可以明确关闭 getUserMedia 返回的 MediaStream 但没有

您还需要在从麦克风获得的 MediaStream 中的每个 MediaStreamTrack 上调用 stop()

this.stream.getTracks().forEach((track) => track.stop());

https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamTrack/stop https://developer.mozilla.org/en-US/docs/Web/API/MediaStream/getTracks