how ( stop,exit ) video in webrtc navigator user media JavaScript

前端 未结 2 489
灰色年华
灰色年华 2020-12-03 16:13

how i stop and exit in pure js, stream webcam in WEBRTC api js , i have in my code the following script :



        
相关标签:
2条回答
  • 2020-12-03 16:25

    What Philipp says. Also clear all references to the stream so it can be freed. Here you have a bug:

    live.src = stream;
    

    is wrong (src takes a URL, not a stream). Luckily it never runs since window.URL exists in all browsers that do WebRTC. But createObjectURL causes the camera to stay on. Instead do this:

    if (typeof live.srcObject == "object") {
        live.srcObject = stream;
    } else {
        live.src = window.URL.createObjectURL(stream)
    }
    

    Or just live.srcObject = stream as srcObject is implemented in all the WebRTC browsers by now (Chrome 54+). It handles resources correctly, so when you later do live.srcObject = null the browser knows it can garbage collect the stream (and turn off the camera should you have missed calling track.stop() on any of the tracks).

    createObjectURL is terrible and deprecated, and leaves resources allocated until page navigation unless you remember to revokeObjectURL. It's why your camera never stops on its own, in case you were wondering, so if you see this pattern in code, please help stamp it out.

    Compare

    Try these for comparison. Video disappears after 2 seconds, but keep an eye on your camera light and the in-browser recording indicator. First with srcObject (https fiddle for Chrome):

    (Cam indicator and light should go out after ~10 seconds in Firefox; ~20 seconds in Chrome.)

    var wait = ms => new Promise(resolve => setTimeout(resolve, ms));
    
    navigator.mediaDevices.getUserMedia({video: true})
      .then(stream => video.srcObject = stream)
      .then(() => wait(2000))
      .then(() => video.srcObject = null)
      .catch(e => console.log(e.name + ": "+ e.message));
    <video id="video" width="160" height="120" autoplay></video>

    Then with createObjectURL (without revokeObjectURL) (https fiddle for Chrome):

    (Stays on forever in both browsers.)

    var wait = ms => new Promise(resolve => setTimeout(resolve, ms));
    
    navigator.mediaDevices.getUserMedia({video: true})
      .then(stream => video.src = URL.createObjectURL(stream))
      .then(() => wait(2000))
      .then(() => video.srcObject = null)
      .catch(e => console.log(e.name + ": "+ e.message));
    <video id="video" width="160" height="120" autoplay></video>

    track.stop() called explicitly will stop it, but only if you've stopped all tracks, which can be easier than it sounds in general given that tracks can be cloned now. So avoid createObjectURL.

    0 讨论(0)
  • 2020-12-03 16:50

    You end a stream by closing all of its tracks: stream.getTracks().forEach(function(track) { track.stop(); })

    0 讨论(0)
提交回复
热议问题