无法停止使用javascript录制

时间:2019-02-25 15:40:32

标签: javascript html laravel

我正在显示一个波形以可视化麦克风输入。我正在执行以下代码。

function micWaveForm (allowScan) {
"use strict";
var paths = document.getElementsByTagName('path');
var visualizer = document.getElementById('visualizer');
var mask = visualizer.getElementById('mask');
var path;
var report = 0;

var soundAllowed = function (stream) {
    //Audio stops listening in FF without // window.persistAudioStream = stream;
    //https://bugzilla.mozilla.org/show_bug.cgi?id=965483
    //https://support.mozilla.org/en-US/questions/984179
    window.persistAudioStream = stream;
    var audioContent = new AudioContext();
    var audioStream = audioContent.createMediaStreamSource( stream );
    var analyser = audioContent.createAnalyser();
    audioStream.connect(analyser);
    analyser.fftSize = 1024;

    var frequencyArray = new Uint8Array(analyser.frequencyBinCount);
    visualizer.setAttribute('viewBox', '0 0 255 255');

    //Through the frequencyArray has a length longer than 255, there seems to be no
    //significant data after this point. Not worth visualizing.
    for (var i = 0 ; i < 255; i++) {
        path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        path.setAttribute('stroke-dasharray', '0');
        mask.appendChild(path);
    }
    var doDraw = function () {
        requestAnimationFrame(doDraw);
        analyser.getByteFrequencyData(frequencyArray);
        var adjustedLength;
        for (var i = 0 ; i < 255; i++) {
            adjustedLength = Math.floor(frequencyArray[i]) - (Math.floor(frequencyArray[i]) % 5);
            paths[i].setAttribute('d', 'M '+ (i) +',255 l 0,-' + adjustedLength);
        }
    }
    doDraw();

}

var soundNotAllowed = function (error) {
    console.log(error);
}


if (allowScan) {
    navigator.getUserMedia({audio:true}, soundAllowed, soundNotAllowed);
} else {
    //Stop the recording
}
};

allowScan变量是一个开始和停止记录的布尔值。当我按下带有代码navigator.getUserMedia();的按钮时,它开始了,然后我试图停止它,但是没有任何效果。有禁用麦克风的方法吗?

1 个答案:

答案 0 :(得分:0)

在您的soundAllowed(stream)函数中,假设您仅使该媒体轨道处于活动状态,则可以通过执行stream.getTracks()[0].stop()来停止记录。