WebRTC学习笔记一 简单示例

一、捕获本地媒体流getUserMedia

1.index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div>
        <button id="start">开始录制</button>
        <button id="stop">停止录制</button>
    </div>
    <div>
        <video autoplay controls id="stream"></video>
    </div>
    <script>
        // 只获取视频
        let constraints = {audio: false, video: true}; 
        let startBtn = document.getElementById('start')
        let stopBtn = document.getElementById('stop')
        let video = document.getElementById('stream')
        startBtn.onclick = function() {
            navigator.getUserMedia(constraints, function(stream) {
                video.srcObject = stream;
                window.stream = stream;
            }, function(err) {
                console.log(err)
            })
        }
        stopBtn.onclick = function() {
            video.pause();
        }
    </script>
</body>
</html>

部署本地服务器后,chrome中访问192.168.11.129:9050会报错:navigator.getUserMedia is not a function。原因是,Chrome 47以后,getUserMedia API只能允许来自“安全可信”的客户端的视频音频请求,如HTTPS和本地的Localhost。所以将访问地址改成localhost:9050即可。

二、同网页示例

例子来源:https://codelabs.developers.google.com/codelabs/webrtc-web/#4

1.index.html

 <!DOCTYPE html>
 <html>
​
     <head>
         <title>Realtime communication with WebRTC</title>
         <style>
             body {
                 font-family: sans-serif;
             }
     
             video {
                 max-width: 100%;
                 width: 320px;
             }
         </style>
     </head>
​
     <body>
         <h1>Realtime communication with WebRTC</h1>
     
         <video id="localVideo" autoplay playsinline></video>
         <video id="remoteVideo" autoplay playsinline></video>
     
         <div>
             <button id="startButton">开始</button>
             <button id="callButton">调用</button>
             <button id="hangupButton">挂断</button>
         </div>
        <!-- 适配各浏览器 API 不统一的脚本 -->
        <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
         </script>
 </body>
​
</html>

2.main.js

'use strict';
​
//log
function trace(text) {
  text = text.trim();
  const now = (window.performance.now() / 1000).toFixed(3);
  console.log(now, text);
}
​
// 设置两个video,分别显示本地视频流和远端视频流
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');
​
localVideo.addEventListener('loadedmetadata', logVideoLoaded);
remoteVideo.addEventListener('loadedmetadata', logVideoLoaded);
remoteVideo.addEventListener('onresize', logResizedVideo);
​
function logVideoLoaded(event) {
  const video = event.target;
  trace(`${video.id} videoWidth: ${video.videoWidth}px, ` +
        `videoHeight: ${video.videoHeight}px.`);
}
​
function logResizedVideo(event) {
  logVideoLoaded(event);
  if (startTime) {
    const elapsedTime = window.performance.now() - startTime;
    startTime = null;
    trace(`Setup time: ${elapsedTime.toFixed(3)}ms.`);
  }
}
​
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个基于 WebRTC 的视频通话示例: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>WebRTC Video Chat Example</title> </head> <body> <video id="localVideo" autoplay></video> <video id="remoteVideo" autoplay></video> <script> // Get local video stream navigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then(function(stream) { var localVideo = document.getElementById('localVideo'); localVideo.srcObject = stream; }) .catch(function(error) { console.log('getUserMedia error: ', error); }); // Create PeerConnection var pc = new RTCPeerConnection(); // Add local stream to PeerConnection var localStream = document.getElementById('localVideo').srcObject; localStream.getTracks().forEach(function(track) { pc.addTrack(track, localStream); }); // Handle incoming remote stream pc.ontrack = function(event) { var remoteVideo = document.getElementById('remoteVideo'); remoteVideo.srcObject = event.streams[0]; }; // Create offer and set local description pc.createOffer() .then(function(offer) { return pc.setLocalDescription(offer); }) .then(function() { // Send offer to remote peer console.log('Local description set:', pc.localDescription); }) .catch(function(error) { console.log('createOffer error: ', error); }); </script> </body> </html> ``` 这个示例使用 `getUserMedia` 方法获取本地视频和音频流,并将其添加到 `RTCPeerConnection` 中。然后,它创建一个 offer 并将其设置为本地描述符,最后将 offer 发送给远程对等端。当远程对等端接收到 offer 后,它将创建一个 answer 并将其设置为远程描述符,然后将 answer 发送回来。一旦本地和远程描述符都设置好了,视频通话就可以开始了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值