设备权限调试
<!-- 步骤2:添加视频显示容器 -->
<video id="videoPreview" autoplay muted playsinline width="640"></video>
<script>
// 步骤3:定义全局引用
const videoElement = document.getElementById('videoPreview');
// 步骤4:增强版初始化函数
async function initCamera() {
try {
console.log('[调试] 开始初始化设备'); // 调试输出
// 步骤5:请求媒体设备权限
const stream = await navigator.mediaDevices.getUserMedia({
video: {
width: { ideal: 1280 },
height: { ideal: 720 },
facingMode: "user"
},
audio: true
});
console.log('[调试] 获得媒体流:', stream); // 调试输出
// 步骤6:绑定视频流
videoElement.srcObject = stream;
// 步骤7:处理自动播放策略
videoElement.play().catch(err => {
console.error('自动播放错误:', err);
videoElement.muted = true;
videoElement.play();
});
} catch (err) {
// 步骤8:增强错误处理
console.error('[错误详情]', err);
showErrorAlert(err.name);
}
}
// 步骤9:可视化错误提示
function showErrorAlert(errorType) {
const errorMap = {
NotAllowedError: '❌ 用户拒绝了权限请求',
NotFoundError: '📷 未找到视频设备',
NotReadableError: '🔒 设备已被其他程序占用',
OverconstrainedError: '⚙️ 无法满足分辨率要求',
SecurityError: '🛡️ 必须在安全上下文(HTTPS/localhost)中运行'
};
alert(errorMap[errorType] || '🌐 未知错误,请查看控制台');
}
// 步骤10:初始设备检测
navigator.mediaDevices.enumerateDevices()
.then(devices => {
console.log('[设备列表]', devices);
if (!devices.some(d => d.kind === 'videoinput')) {
alert('⚠️ 未检测到摄像头设备');
}
});
</script>