webrtc学习----前端推流拉流,单网页版
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>推拉流</title>
</head>
<body>
<video id="pushVideo" src="" playsinline autoplay muted height="300" width="400"></video>
<video id="pullVideo" playsinline autoplay muted height="300" width="400"></video>
<div id="pushBtn">推流</div>
<div id="pullBtn">拉流</div>
<script>
const pushVideo = document.getElementById('pushVideo');
const pullVideo = document.getElementById('pullVideo');
const pushBtn = document.getElementById('pushBtn');
const pullBtn = document.getElementById('pullBtn');
let pushStream;
// 开启摄像头,video播放视频流
const getStream = async() =>{
if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)console.log('不支持:getUserMedia');
pushStream = await navigator.mediaDevices.getUserMedia({video:true});
pushVideo.srcObject = pushStream;
}
// 开启推流拉流
const startPull = async () => {
const pushRtcCon = new RTCPeerConnection();
const pullRtcCon = new RTCPeerConnection();
// pullRtcCon接收到pushRtcCon(推流)传递的icecandidate,pushRtcCon(推流)执行addIceCandidate
pullRtcCon.addEventListener('icecandidate',async (event)=>{
if(event.candidate) await pushRtcCon.addIceCandidate(event.candidate);
});
// pushRtcCon接收到pullRtcCon(拉流)传递的icecandidate,pullRtcCon(拉流)执行addIceCandidate
pushRtcCon.addEventListener('icecandidate',async (event)=>{
if(event.candidate) await pullRtcCon.addIceCandidate(event.candidate);
});
// 拉流监听track数据
pullRtcCon.addEventListener('track', (event)=>{
pullVideo.srcObject = event.streams[0];//必须得点第二下才播放
});
// 推流添加track
pushStream.getTracks().forEach(async (track)=>{
await pushRtcCon.addTrack(track,pushStream)
});
// 推流创建offer
let offer = await pushRtcCon.createOffer({offerToReceiveAudio: 0,offerToReceiveVideo: 1});
// 推流端设置LocalDescription
await pushRtcCon.setLocalDescription(offer);
// 拉流端设置RemoteDescription
await pullRtcCon.setRemoteDescription({type: 'offer', sdp: offer.sdp});
// 拉流端创建answer
let answer = await pullRtcCon.createAnswer();
// 拉流端设置LocalDescription
await pullRtcCon.setLocalDescription(answer);
// 推流端设置RemoteDescription
await pushRtcCon.setRemoteDescription(answer);
}
pushBtn.addEventListener('click',getStream);
pullBtn.addEventListener('click',startPull);
</script>
</body>
</html>