项目场景:
h5页面,使用浏览器提供的navigator.mediaDevices.getUserMedia方法,唤起摄像头,然后进行视频通话。
问题描述
苹果手机通过navigator.mediaDevices.getUserMedia方法,调用摄像头,会出现黑屏问题,安卓手机可以正常显示,但苹果手机不行,这个不存在是Safari拒绝调用摄像头的原因,因为我检查了权限,都是同意的。
原来的代码
navigator.mediaDevices.getUserMedia({video: isVideo, audio: true}).then(
function (_stream: MediaStream) {
myVideoRef.current.srcObject = _stream
}
).catch(function (error:any) {
console.error('无法访问摄像头:', error);
});
// 页面代码
<video id={styles.otherVideo} autoPlay ref={myVideoRef}></video>
解决方案:
useEffect(() => {
// 解决苹果手机打开摄像头黑屏问题
let videoElement= document.createElement('video');
videoElement.setAttribute('autoplay', '');
videoElement.setAttribute('muted', '');
videoElement.setAttribute('playsinline', '');
videoElement.id = "my"
// 插入到页面中
setTimeout(() => {
let videoCon = document.getElementById('videoCon')
videoCon?.insertBefore(videoElement,videoCon.firstChild)
},10);
// 获取视频流,并赋值给新创建的dom元素
navigator.mediaDevices.getUserMedia({video: isVideo, audio: true}).then(
function (_stream: MediaStream) {
videoElement.srcObject = _stream
}
).catch(function (error:any) {
console.error('无法访问摄像头:', error);
});
return () => {
//组件销毁 关闭摄像头
}
}, [])
通过查询相关文档,排除掉了https安全协议,以及safari是否拒绝使用摄像头等各种问题,最终在Stack
Overflow上发现此类问题,最重要的解决代码就是设置这个属性,
video.setAttribute(‘playsinline’, ‘’);
或者直接这样写<video autoPlay playsInline ></video>