本文介绍如果通过html代码在浏览器中采集和播放音视频数据。

1 html代码,用于显示视频

<html>
	<head>
		<title>WebRTC capture video and audio</title>
	</head>
	<body>
		<video autoplay playsinline id = "player"></video>
		<script src = "./client.js"></script>
	</body>
</html>

2 js代码,用于获取视频流

'use strict'

//后去到video标签
var videoplay = document.querySelector('video#player');

//将流赋值给video标签
function gotMediaStream(stream){
	videoplay.srcObject = stream;
}

//打印错误日志
function handleError(err){
	console.log('getUserMedia error : ', err);
}

if(!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){
	console.log('getUserMedia is not supported');
}else{
	var constraints = {
		video : true,
		audio : true
	}

	navigator.mediaDevices.getUserMedia(constraints)
	.then(gotMediaStream)
	.catch(handleError)
}

通过以上js和html代码,就能将采集出摄像头的数据和音频数据。
但是以上方法是有浏览器的兼容性的问题。所以需要在js里面加入以下开源库

https://webrtc.github.io/adapter/adapter-latest.js

完整html代码

<html>
	<head>
		<title>WebRTC capture video and audio</title>
	</head>
	<body>
		<video autoplay playsinline id = "player"></video>
		<script src = "https://webrtc.github.io/adapter/adapter-latest.js"></script>
		<script src = "./client.js"></script>
	</body>
</html>

预览效果
html视频采集效果预览

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐