我使用以下JavaScript代码打开了一个网络摄像头:
const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });
是否有任何JavaScript代码停止或关闭网络摄像头?
我使用以下JavaScript代码打开了一个网络摄像头:
const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });
是否有任何JavaScript代码停止或关闭网络摄像头?
当前回答
试试下面的方法:
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();
其他回答
您可以直接使用成功处理程序中返回给getUserMedia的流对象来结束流。如。
localMediaStream.stop()
视频。Src =""或null只会从视频标签中删除源。它不会释放硬件。
下面的代码适用于我:
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();
}
假设我们有流式视频标签,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;
启动和停止网络摄像头,(更新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();
使用下列函数:
// stop both mic and camera
function stopBothVideoAndAudio(stream) {
stream.getTracks().forEach(function(track) {
if (track.readyState == 'live') {
track.stop();
}
});
}
// stop only camera
function stopVideoOnly(stream) {
stream.getTracks().forEach(function(track) {
if (track.readyState == 'live' && track.kind === 'video') {
track.stop();
}
});
}
// stop only mic
function stopAudioOnly(stream) {
stream.getTracks().forEach(function(track) {
if (track.readyState == 'live' && track.kind === 'audio') {
track.stop();
}
});
}