苹果手机通过getUserMedia唤起摄像头,出现黑屏问题

本文讲述了在H5页面中,使用navigator.mediaDevices.getUserMedia在苹果手机Safari上调用摄像头出现黑屏的问题,通过添加`playsinline`属性和相应代码调整,成功解决了这个问题。
摘要由CSDN通过智能技术生成

项目场景:

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>

stackoverflow问题

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值