track.stop 不再关闭相机

Lel*_*eta 2 javascript jquery mediadevices

我有一个网页,我希望用户用他的笔记本电脑/手机相机拍照。一旦他点击按钮,就会显示一个模式,下面的 js 将启动相机流来拍照:

    function startStreaming() {
        if (null != cameraStream) {
            var track = cameraStream.getTracks()[0];
            track.stop();
            stream.load();
            cameraStream = null;
        }
        //const audioSource = audioInputSelect.value;
        const videoSource = videoSelect.value;
        const constraints = {
            //audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
            video: {
                deviceId: videoSource ? {
                    exact: videoSource
                } : undefined
            }
        };
        navigator.mediaDevices.getUserMedia(constraints).then(gotStream).then(gotDevices).catch(handleError);
        var mediaSupport = 'mediaDevices' in navigator;
        if (mediaSupport && null == cameraStream) {
            const videoSource = videoSelect.value;
            const constraints = {
                video: {
                    deviceId: videoSource ? {
                        exact: videoSource
                    } : undefined
                }
            };
            navigator.mediaDevices.getUserMedia(constraints)
                .then(function (mediaStream) {
                    cameraStream = mediaStream;
                    stream.srcObject = mediaStream;
                    stream.play();
                })
                .catch(handleError);
        } else {
            alert('Your browser does not support media devices.');
            return;
        }
    }
Run Code Online (Sandbox Code Playgroud)

这是由

            $('#photoStudio').on('show.bs.modal', function (event) {
                navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);
                startStreaming();
            });
Run Code Online (Sandbox Code Playgroud)

然后,当我关闭模式时,我想停止流媒体,但相机旁边的 LED 指示灯仍然亮着)

            $('#photoStudio').on('hide.bs.modal', function (event) {
                stopStreaming();
            });
Run Code Online (Sandbox Code Playgroud)

哪里stopStreaming()

    function stopStreaming() {
        if (null != cameraStream) {
            var track = cameraStream.getTracks()[0];
            track.stop();
            stream.load();
            cameraStream = null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我没有收到任何类型的错误,也找不到调试相机为何仍在运行的方法。我在 stopStreaming 函数中遗漏了什么吗?

小智 7

如果任何轨道尚未停止,那么您的相机仍将处于活动状态。在您的stopStreaming函数中,您仅停止返回数组中的第一首曲目。

如果您迭代曲目,您可能会发现当前没有的曲目:

    function stopStreaming() {
        if (null != cameraStream) {
            var tracks = cameraStream.getTracks();
           // stop all the tracks, not just the first
            tracks.forEach((track) => {
                track.stop();
           });
            stream.load();
            cameraStream = null;
        }
    }
Run Code Online (Sandbox Code Playgroud)