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

核能气质少年 提交于 2019-11-27 14:51:51

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!