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