How to use js on the front end to turn on and off the camera and its indicator light

In fact, what this article mainly wants to explain is how to turn off the camera and its indicator light, because this thing really bothers me, and it is not that difficult to turn on the camera, just call the navigator.mediaDevices.getUserMedia method, the specific is I won’t go into details, just upload the code directly (the HTML structure is a video tag and two button buttons, so only the js part is included)

 const video = document.querySelector('#video')
//开启摄像头按钮
 const btn1 = document.querySelector('#btn1')
//关闭摄像头按钮
const btn2 = document.querySelector('#btn2')
let mediaStreamTrack = null

btn1.addEventListener('click', async () => {
                await navigator.mediaDevices.getUserMedia({ video: true })
                    .then((staream) => {
//这里保存下来stream对象只是为了后续关闭摄像头的时候使用
                        mediaStreamTrack = stream
                        video.srcObject = staream
                    })
        })

After turning on the camera, the key point is, how do I turn off the camera and its indicator light!!!!

Turning off the camera actually needs to use the stream object we saved before, loop the getVideoTracks() method of the stream object and then call the stop() method for each content in it, some people may wonder, why do we need to loop here? The purpose of the loop In fact, it is to stop the video and audio together. If you don’t turn on the audio, you don’t need to loop. I only turned on the video here.

btn2.addEventListener('click',() => {
            mediaStreamTrack.getVideoTracks().forEach(track => {
            track.stop()
        })
      })

After writing this code, you will find that the content in the video tag is gone. It is a black screen, but the indicator light next to your camera is still on. This is because you turned off the camera, but not completely, although the content is gone. , In fact, black frames are still being pushed all the time. The initial judgment is that mediaStreamTrack.getVideoTracks() returns a new stream (if the judgment is wrong, you can correct it in time). At this time, you can add a string of codes to make video srcObject=null, This will turn off the light

btn2.addEventListener('click',() => {
            mediaStreamTrack.getVideoTracks().forEach(track => {
            track.stop()
        })
        video.value.srcObject = null
      })

This is because of the powerful garbage collection mechanism, hahaha, it ends here

Guess you like

Origin blog.csdn.net/LMCyyds/article/details/131010790