不需要引用插件
效果展示图:此演示由于没有外接摄像头 默认读取到电脑影像
<div class="flex">
<div>
<button (click)="openMedia()">开启摄像头</button>
<button (click)="closeMedia()">关闭摄像头</button>
<div style="height:482px">
<video style="display: none;" class="src-video" width="460px" height="460px" autoplay="autoplay" ></video>
</div>
</div> <!-- 摄像头画面1 -->
<div>
<button (click)="openMedia1()" >开启摄像头</button>
<button (click)="closeMedia1()" class="left5" >关闭摄像头</button>
<div style="height:482px">
<video style="display: none;" class="src-video1" width="460px" height="460px" autoplay="autoplay"></video>
</div>
</div> <!-- 摄像头画面2 -->
</div>
// 首先获取 到摄像头 id
getDeviceIds(){
this.srcVideo = document.querySelector('video.src-video');
this.srcVideo1= document.querySelector('video.src-video1');
navigator.mediaDevices.enumerateDevices().then((devicesList) => {
// console.log(devicesList)
for(var i = 0; i < devicesList.length; i++) {
if(devicesList[i]['kind'] == 'videoinput') {
this.deviceIds.push(devicesList[i]['deviceId'])
}
}
});
console.log("ID",this.deviceIds, this.srcVideo,this.srcVideo1)
}
//开启摄像头1
openMedia() {
this.srcVideo.style.display = 'block';
let constraints = {
audio: false, //音频轨道
video: {
width: 300,
height: 300,
deviceId: this.deviceIds[0] //deviceIds[]取值可以根据获取到的id变换
} //视频轨道
}
let mediaPromise = navigator.mediaDevices.getUserMedia(constraints);
mediaPromise.then((stream)=> {
console.log("调整1",mediaPromise,stream)
/* 使用这个stream stream */
this.mediaStream = stream;
this.srcVideo.srcObject = stream;
console.log(this.mediaStream)
this.srcVideo.play();
}).catch(function(err) {
/* 处理error */
console.log('摄像头1',err);
});
navigator.mediaDevices.enumerateDevices().then((devicesList) => {
console.log('开启',devicesList)
});
}
// 关闭摄像头1
closeMedia = function() {
this.mediaStream.getTracks().forEach(track => {
track.stop();
});
this.srcVideo.style.display = 'none';
};
//开启摄像头2
openMedia1() {
console.log(this.deviceIds)
this.srcVideo1.style.display = 'block';
let constraints = {
audio: false, //音频轨道
video: {
width: 300,
height: 300,
deviceId: this.deviceIds[2]
} //视频轨道
}
let mediaPromise = navigator.mediaDevices.getUserMedia(constraints);
mediaPromise.then((stream)=> {
/* 使用这个stream stream */
this.mediaStream1 = stream;
this.srcVideo1.srcObject = stream;
this.srcVideo1.play();
}).catch(function(err) {
/* 处理error */
console.log('摄像头2',err);
});
};
// 关闭摄像头2
closeMedia1() {
this.mediaStream1.getTracks().forEach(track => {
track.stop();
});
this.srcVideo1.style.display = 'none';
};