// 获取摄像头
function getUserMedia(video, success, error) {
if (window.navigator.mediaDevices.getUserMedia) {
//最新的标准API
window.navigator.mediaDevices.getUserMedia(video).then(success).catch(error);
} else if (window.navigator.webkitGetUserMedia) {
//webkit核心浏览器
window.navigator.webkitGetUserMedia(video, success, error)
} else if (window.navigator.mozGetUserMedia) {
//firfox浏览器
window.navigator.mozGetUserMedia(video, success, error);
} else if (window.navigator.getUserMedia) {
//旧版API
window.navigator.getUserMedia(video, success, error);
} else {
window.alert('不支持访问用户媒体!');
}
}
function success(stream) {
window.mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[0];
//兼容webkit核心浏览器
let CompatibleURL = window.URL || window.webkitURL;
//将视频流设置为video元素的源
video.srcObject = stream;
video.play();
}
function error(error) {
window.alert(`访问用户媒体设备失败${error.name}, ${error.message}`);
}
//关闭摄像头
window.mediaStreamTrack && window.mediaStreamTrack.stop();