WebRTC(四) Web端音視頻數據採集及處理

本文介紹如果通過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視頻採集效果預覽

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章