我使用以下JavaScript代码打开了一个网络摄像头:
const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });
是否有任何JavaScript代码停止或关闭网络摄像头?
我使用以下JavaScript代码打开了一个网络摄像头:
const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });
是否有任何JavaScript代码停止或关闭网络摄像头?
当前回答
启动和停止网络摄像头,(更新2020 React es6)
开启Web摄像头
stopWebCamera =()=>
//Start Web Came
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
//use WebCam
navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
this.localStream = stream;
this.video.srcObject = stream;
this.video.play();
});
}
}
停止网络摄像头或视频播放一般
stopVideo =()=>
{
this.video.pause();
this.video.src = "";
this.video.srcObject = null;
// As per new API stop all streams
if (this.localStream)
this.localStream.getTracks().forEach(track => track.stop());
}
停止网络摄像头功能,即使视频流:
this.video.src = this.state.videoToTest;
this.video.play();
其他回答
不要使用stream.stop(),它已被弃用
MediaStream用法
使用stream.getTracks()。forEach(track => track.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();
有溪流形式成功的参考吗
var streamRef;
var handleVideo = function (stream) {
streamRef = stream;
}
//this will stop video and audio both track
streamRef.getTracks().map(function (val) {
val.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();
});
当然,这将关闭所有活动的视频轨道。如果你有多个,你应该选择相应的。
下面的代码适用于我:
public vidOff() {
let stream = this.video.nativeElement.srcObject;
let tracks = stream.getTracks();
tracks.forEach(function (track) {
track.stop();
});
this.video.nativeElement.srcObject = null;
this.video.nativeElement.stop();
}