内容简介:MediaDevices.getUserMedia() 会提示用户给予使用媒体输入的许可,媒体输入会产生一个它返回一个返回的promise对象可能既不会resolve也不会reject,因为用户不是必须选择允许或拒绝。
MediaDevices.getUserMedia() 会提示用户给予使用媒体输入的许可,媒体输入会产生一个
MediaStream
,里面包含了请求的媒体类型的轨道。此流可以包含一个视频轨道(来自硬件或者虚拟视频源,比如相机、视频采集设备和屏幕共享服务等等)、一个音频轨道(同样来自硬件或虚拟音频源,比如麦克风、A/D转换器等等),也可能是其它轨道类型。
它返回一个
Promise
对象,成功后会 resolve
回调一个
MediaStream
对象。若用户拒绝了使用权限,或者需要的媒体源不可用, promise
会 reject
回调一个 PermissionDeniedError
或者 NotFoundError
。
返回的promise对象可能既不会resolve也不会reject,因为用户不是必须选择允许或拒绝。
通常你可以使用
navigator.mediaDevices
来获取
MediaDevices
,例如:
navigator.mediaDevices.getUserMedia(constraints)
.then(function(stream) {
/* 使用这个stream stream */
})
.catch(function(err) {
/* 处理error */
});
关于参数 constraints
同时请求音频和视频
{ audio: true, video: true }
使用1280x720的摄像头分辨率
{ audio: true, video: { width: 1280, height: 720 } }
在移动设备优先使用前置摄像头
{ audio: true, video: { facingMode: “user” } }
强制使用后置摄像头
{ audio: true, video: { facingMode: { exact: “environment” } } }
vue项目实战
<Modal v-model="photoDialog">
<p slot="header" style="text-align:left">
<Icon type="android-camera"></Icon>
<span>打卡</span></p>
<div style="text-align:center">
<Spin size="large" fix v-if="spinShow"></Spin>
<video v-show="!took" ref="video" width="320" height="240" autoplay></video>
<canvas v-show="took" ref="canvas" width="320" height="240"></canvas>
</div>
<div slot="footer" style="text-align: right">
<span v-if="!took" @click="takePhoto" style="margin: 3px 0; display: inline; margin-left: 10px;"><Button type="primary">拍照</Button></span>
<span v-if="took" @click="initCamera" style="margin: 3px 0; display: inline; margin-left: 10px;"><Button>重拍</Button></span>
<span v-if="took" @click="" style="margin: 3px 0; display: inline; margin-left: 10px;"><Button type="primary">提交</Button></span>
</div>
</Modal>
export default {
data() {
return {
photoDialog:
false spinShow:
false,
took: false,
stream: null,
took: false,
attendance: {
content: ''
}
}
},
watch: {
photoDialog(val, oldVal) {
if (!val) {
this.stream.getVideoTracks()[0].stop(); //监听弹窗状态来关闭摄像头
}
},
},
methods: {
ClockIn() {
this.photoDialog = true;
this.initCamera()
},
initCamera() {
let _this = this;
_this.spinShow = true;
_this.took = false;
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({
'video': true
}).then(function(stream) {
_this.stream = stream;
_this.$refs.video.src = window.URL.createObjectURL(stream);
setTimeout(function() {
_this.spinShow = false;
},
800)
}).
catch(function(err) {
console.log(err);
});
}
},
takePhoto() {
var context = this.$refs.canvas.getContext('2d');
context.drawImage(this.$refs.video, 0, 0, 320, 240);
this.attendance.content = this.$refs.canvas.toDataURL('image/jpeg');
this.stream.getVideoTracks()[0].stop();
this.took = true
},
}
}
深自缄默,如云漂泊 本文链接: http://zc95.github.io/2018/07/28/mediaDevices/
以上所述就是小编给大家介绍的《MediaDevices.getUserMedia()》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。