我使用以下JavaScript代码打开了一个网络摄像头:
const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });
是否有任何JavaScript代码停止或关闭网络摄像头?
我使用以下JavaScript代码打开了一个网络摄像头:
const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });
是否有任何JavaScript代码停止或关闭网络摄像头?
当前回答
有溪流形式成功的参考吗
var streamRef;
var handleVideo = function (stream) {
streamRef = stream;
}
//this will stop video and audio both track
streamRef.getTracks().map(function (val) {
val.stop();
});
其他回答
试试下面的方法:
var mediaStream = null;
navigator.getUserMedia(
{
audio: true,
video: true
},
function (stream) {
mediaStream = stream;
mediaStream.stop = function () {
this.getAudioTracks().forEach(function (track) {
track.stop();
});
this.getVideoTracks().forEach(function (track) { //in case... :)
track.stop();
});
};
/*
* Rest of your code.....
* */
});
/*
* somewhere insdie your code you call
* */
mediaStream.stop();
因为你需要音轨来关闭流,你需要流对象来获得音轨,我在Muaz Khan的回答的帮助下使用的代码如下:
if (navigator.getUserMedia) {
navigator.getUserMedia(constraints, function (stream) {
videoEl.src = stream;
videoEl.play();
document.getElementById('close').addEventListener('click', function () {
stopStream(stream);
});
}, errBack);
function stopStream(stream) {
console.log('stop called');
stream.getVideoTracks().forEach(function (track) {
track.stop();
});
当然,这将关闭所有活动的视频轨道。如果你有多个,你应该选择相应的。
假设我们有流式视频标签,id是video - <video id="video"></video>,那么我们应该有以下代码-
var videoEl = document.getElementById('video');
// now get the steam
stream = videoEl.srcObject;
// now get all tracks
tracks = stream.getTracks();
// now close each track by having forEach loop
tracks.forEach(function(track) {
// stopping every track
track.stop();
});
// assign null to srcObject of video
videoEl.srcObject = null;
有溪流形式成功的参考吗
var streamRef;
var handleVideo = function (stream) {
streamRef = stream;
}
//this will stop video and audio both track
streamRef.getTracks().map(function (val) {
val.stop();
});
FF, Chrome和Opera已经开始通过导航器公开getUserMedia。mediaDevices现在是标准(可能会改变:)
在线演示
navigator.mediaDevices.getUserMedia({audio:true,video:true})
.then(stream => {
window.localStream = stream;
})
.catch( (err) =>{
console.log(err);
});
// later you can do below
// stop both video and audio
localStream.getTracks().forEach( (track) => {
track.stop();
});
// stop only audio
localStream.getAudioTracks()[0].stop();
// stop only video
localStream.getVideoTracks()[0].stop();