JavaScript实现视频共享

1.视频共享webrtc-master

index.html

<!DOCTYPE html>
<html>
<head>
  <script type='text/javascript' src='https://cdn.scaledrone.com/scaledrone.min.js'></script>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <style>
    body {
      display: flex;
      height: 100vh;
      margin: 0;
      align-items: center;
      justify-content: center;
      padding: 0 50px;
      font-family: -apple-system, BlinkMacSystemFont, sans-serif;
    }
    video {
      max-width: calc(50% - 100px);
      margin: 0 50px;
      box-sizing: border-box;
      border-radius: 2px;
      padding: 0;
      box-shadow: rgba(156, 172, 172, 0.2) 0px 2px 2px, rgba(156, 172, 172, 0.2) 0px 4px 4px, rgba(156, 172, 172, 0.2) 0px 8px 8px, rgba(156, 172, 172, 0.2) 0px 16px 16px, rgba(156, 172, 172, 0.2) 0px 32px 32px, rgba(156, 172, 172, 0.2) 0px 64px 64px;
    }
    .copy {
      position: fixed;
      top: 10px;
      left: 50%;
      transform: translateX(-50%);
      font-size: 16px;
      color: rgba(0, 0, 0, 0.5);
    }
  </style>
</head>
<body>
  <div class="copy">Send your URL to a friend to start a video call</div>
  <video id="localVideo" autoplay muted></video>
  <video id="remoteVideo" autoplay></video>
  <script src="script.js"></script>
</body>
</html>

script.js

// Generate random room name if needed
if (!location.hash) {
  location.hash = Math.floor(Math.random() * 0xFFFFFF).toString(16);
}
const roomHash = location.hash.substring(1);

// TODO: Replace with your own channel ID
const drone = new ScaleDrone('yiS12Ts5RdNhebyM');
// Room name needs to be prefixed with 'observable-'
const roomName = 'observable-' + roomHash;
const configuration = {
  iceServers: [{
    urls: 'stun:stun.l.google.com:19302'
  }]
};
let room;
let pc;


function onSuccess() {};
function onError(error) {
  console.error(error);
};

drone.on('open', error => {
  if (error) {
    return console.error(error);
  }
  room = drone.subscribe(roomName);
  room.on('open', error => {
    if (error) {
      onError(error);
    }
  });
  // We're connected to the room and received an array of 'members'
  // connected to the room (including us). Signaling server is ready.
  room.on('members', members => {
    console.log('MEMBERS', members);
    // If we are the second user to connect to the room we will be creating the offer
    const isOfferer = members.length === 2;
    startWebRTC(isOfferer);
  });
});

// Send signaling data via Scaledrone
function sendMessage(message) {
  drone.publish({
    room: roomName,
    message
  });
}

function startWebRTC(isOfferer) {
  pc = new RTCPeerConnection(configuration);

  // 'onicecandidate' notifies us whenever an ICE agent needs to deliver a
  // message to the other peer through the signaling server
  pc.onicecandidate = event => {
    if (event.candidate) {
      sendMessage({'candidate': event.candidate});
    }
  };

  // If user is offerer let the 'negotiationneeded' event create the offer
  if (isOfferer) {
    pc.onnegotiationneeded = () => {
      pc.createOffer().then(localDescCreated).catch(onError);
    }
  }

  // When a remote stream arrives display it in the #remoteVideo element
  pc.ontrack = event => {
    const stream = event.streams[0];
    if (!remoteVideo.srcObject || remoteVideo.srcObject.id !== stream.id) {
      remoteVideo.srcObject = stream;
    }
  };

  navigator.mediaDevices.getUserMedia({
    audio: true,
    video: true,
  }).then(stream => {
    // Display your local video in #localVideo element
    localVideo.srcObject = stream;
    // Add your stream to be sent to the conneting peer
    stream.getTracks().forEach(track => pc.addTrack(track, stream));
  }, onError);

  // Listen to signaling data from Scaledrone
  room.on('data', (message, client) => {
    // Message was sent by us
    if (client.id === drone.clientId) {
      return;
    }

    if (message.sdp) {
      // This is called after receiving an offer or answer from another peer
      pc.setRemoteDescription(new RTCSessionDescription(message.sdp), () => {
        // When receiving an offer lets answer it
        if (pc.remoteDescription.type === 'offer') {
          pc.createAnswer().then(localDescCreated).catch(onError);
        }
      }, onError);
    } else if (message.candidate) {
      // Add the new ICE candidate to our connections remote description
      pc.addIceCandidate(
        new RTCIceCandidate(message.candidate), onSuccess, onError
      );
    }
  });
}

function localDescCreated(desc) {
  pc.setLocalDescription(
    desc,
    () => sendMessage({'sdp': pc.localDescription}),
    onError
  );
}

See more:

其他可以参考屏幕共享 

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
WebRTC(Web Real-Time Communication)是一种支持在浏览器和移动应用程序中进行实时音视频通信的技术。以下是一个基于WebRTC实现视频聊天的简单案例: 1. 创建一个新的WebRTC项目并安装必要的依赖项: ``` npm init npm install --save-dev webpack webpack-dev-server html-webpack-plugin babel-loader babel-core babel-preset-env babel-preset-react npm install --save react react-dom npm install --save webrtc-adapter ``` 2. 创建一个 `index.html` 文件,包含一个视频聊天界面的UI元素。 ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>WebRTC Video Chat</title> </head> <body> <div id="app"></div> <script src="bundle.js"></script> </body> </html> ``` 3. 创建一个 `index.js` 文件,并引入 `react` 和 `react-dom`。 ```javascript import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <h1>Hello, World!</h1>, document.getElementById('app') ); ``` 4. 运行webpack打包,生成 `bundle.js` 文件。 ``` webpack ``` 5. 在 `index.js` 文件中添加WebRTC代码,实现视频聊天功能。 ```javascript import React from 'react'; import ReactDOM from 'react-dom'; // 获取本地视频流 navigator.mediaDevices.getUserMedia({ video: true }) .then(localStream => { // 渲染本地视频 const localVideo = document.createElement('video'); localVideo.srcObject = localStream; localVideo.autoplay = true; document.body.appendChild(localVideo); // 连接到远程视频 const peerConnection = new RTCPeerConnection(); peerConnection.addStream(localStream); peerConnection.createOffer() .then(offer => { return peerConnection.setLocalDescription(offer); }) .then(() => { // 发送SDP信令 const offer = peerConnection.localDescription; // ... }); }) .catch(error => { console.error('getUserMedia error:', error); }); ReactDOM.render( <h1>Hello, World!</h1>, document.getElementById('app') ); ``` 6. 实现SDP信令交换的服务器端代码。这里可以使用Socket.io或其他WebSocket库来实现。 7. 客户端向服务器发送SDP信令,并接收远程视频流。 ```javascript // 连接到信令服务器 const socket = io.connect(); // 发送offer socket.emit('offer', offer); // 接收answer socket.on('answer', answer => { peerConnection.setRemoteDescription(new RTCSessionDescription(answer)); }); // 接收远程视频流 peerConnection.onaddstream = event => { const remoteVideo = document.createElement('video'); remoteVideo.srcObject = event.stream; remoteVideo.autoplay = true; document.body.appendChild(remoteVideo); }; ``` 8. 运行WebRTC应用程序,并进行视频聊天。 以上是一个简单的基于WebRTC实现视频聊天的案例,实际场景中还需要处理一些错误和异常情况,以及实现更复杂的功能,例如音频聊天、屏幕共享等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今晚哒老虎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值