ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

webrtc 点对点聊天 不需要服务器

2022-05-26 00:33:29  阅读:177  来源: 互联网

标签:function console log 点对点 call var 服务器 startId webrtc


<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>视频聊天</title>
  <link rel="stylesheet" type="text/css" href="css/common.css" />
  <link rel="stylesheet" type="text/css" href="css/jquery-ui.css" />
  <!-- <script src="https://unpkg.com/peerjs@1.3.2/dist/peerjs.min.js"></script> -->
  <script src="./js/peerjs.min.js"></script>
  <script src="./js/jquery-1.12.4.js"></script>
  <script src="./js/jquery-ui.js"></script>
  <script>
    var peer = null; 
    var startId = null; 
    var receiveId = null;
    var conn = null;
    var localStream = null;
    
 
    //获取url后面的参数
    getRequest = function() { 
        var url = location.search; 
        var theRequest = new Object(); 
        if (url.indexOf("?") != -1) { 
            let str = url.substr(1); 
            let strs = str.split("&"); 
            for(let i = 0; i < strs.length; i++) { 
                theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]); 
            } 
        } 
        return theRequest; 
    }

    //绑定摄像头列表到下拉框
    function getDevices(deviceInfos) {
        if (deviceInfos===undefined){
            return
        }
        console.log(`设备信息${deviceInfos}`)
        for (let i = 0; i !== deviceInfos.length; ++i) {
          // console.log(deviceInfos[i])
          const deviceInfo = deviceInfos[i];
          const option = document.createElement('option');
          option.value = deviceInfo.deviceId;
          if (deviceInfo.kind === 'videoinput') {
              option.text = deviceInfo.label || `camera ${videoSelect.length + 1}`;
              console.log(option)
              videoSelect.appendChild(option);
          }
        }
    }

    //获取设备错误
    function handleError(error) {
        console.log('navigator.MediaDevices.getUserMedia error: ', error.message, error.name);
    }

    //获取流
    function getStream(stream) {
        console.log('received local stream');
        localStream = stream;
        localVideo.srcObject = localStream; //显示到页面
        // console.log(`localStream${stream}`)
    }

    //开启本地摄像头
    function start() {
        if (localStream) { //停止
            localStream.getTracks().forEach(track => {
                track.stop();
            });
        }
        const videoSource = videoSelect.value;
        const constraints = {
            audio: true,
            video: { width: 6020, deviceId: videoSource ? { exact: videoSource } : undefined }
        };
        navigator.mediaDevices
            .getUserMedia(constraints)
            .then(getStream)
            .then(getDevices)
            .catch(handleError);
    }
    
    //封装发送消息
    function sendMessage(from, to, action) {
        var message = { "from": from, "to": to, "action": action };
        if (!conn) {
            conn = peer.connect(receiveId);
            conn.on('open', () => {
                conn.send(JSON.stringify(message));
                console.log("发消息",message);
            });
        }
        if (conn.open){
            conn.send(JSON.stringify(message));
            console.log(message);
        }
    }
    
    //当此端改变摄像头 请求那边重新call一次 不然画面传不过去
    function pleaseCallMe(){
      sendMessage(startId, receiveId, "pleaseCallMe");
    }


    //页面加载后 
    window.onload = function () {
      var videoSelect = document.querySelector("select#videoSelect")
      var localVideo = document.querySelector("video#localVideo");
      var remoteVideo = document.querySelector("video#remoteVideo");
      var lblFrom = document.querySelector("label#lblFrom");
      var tip = document.querySelector("#tip");
      if (!navigator.mediaDevices ||
          !navigator.mediaDevices.getUserMedia) {
          console.log('webrtc is not supported!');
          alert("webrtc is not supported!");
          return;
      }

      //获取摄像头列表
      navigator.mediaDevices
        .enumerateDevices()
        .then(getDevices)
        .catch(handleError);

      //改变摄像头重新获取流
      videoSelect.onchange = function(){
        start();
        pleaseCallMe(); //让那边重新call 就能同步画面
      }; 
      start(); //默认直接获取流

      $("#dialog-confirm").hide(); //隐藏接收提示框


      //每次使用同一个startId
      if(localStorage.getItem("startId")==null){
        startId = new Date().getTime();
        localStorage.setItem("startId",startId)
      }else{
        startId = localStorage.getItem("startId")
      }

      peer = new Peer(startId);
      console.log(peer)

      peer.on('open', function(id) {
        startId = id;
        console.log('My peer ID is: ' + id);
        console.log(`接收端链接${location.href.replace("self","target")}?startId=${startId}`)
        document.getElementById("receivedUrl").innerHTML = `<a target="_blank" href="${location.href.replace("self","target")}?startId=${startId}">${location.href.replace("self","target")}?startId=${startId}</a>` 
      });

      peer.on('call', function (call) {
        console.log("oncall")
        call.answer(localStream);
      });

      peer.on('connection', function(conn) {
        console.log("被连接",conn);
        receiveId = conn.peer;
        conn.on('data', (data) => {
            var msg = JSON.parse(data);
            console.log("收到消息",msg);
            //收到视频邀请时,弹出询问对话框
            if (msg.action === "call") {
                console.log("call")
                tip.innerHTML = "被别人call"
                lblFrom.innerText = msg.from;
                $("#dialog-confirm").dialog({
                    resizable: false,
                    height: "auto",
                    width: 400,
                    modal: true,
                    buttons: {
                        "Accept": function () {
                            $(this).dialog("close");
                            sendMessage(msg.to, msg.from, "accept");
                        },
                        Cancel: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }

            //接受视频通话邀请后,通知另一端    
            if (msg.action === "accept-ok") {
                console.log("accept-ok call => " + JSON.stringify(msg));
                var call = peer.call(receiveId, localStream);
                call.on('stream', function (stream) {
                    console.log('received remote stream');
                    remoteVideo.srcObject = stream;                            
                });
                tip.innerHTML = "已连接"
            }
        });
      });

    }
  </script>
</head>
<body>
  <div class="container" style="text-align: center;">
    <h1>基于PeerJS的点对点视频聊天程序</h1>
    <p>
      <span style="font-weight: 700;">切换设备</span>
      <select id="videoSelect" style="width:100px"></select>
    </p>
    <p>
      把下方链接发送给你对象即可开始视频啦<br />
      <span>对象链接:</span><span id="receivedUrl">生成中...</span>
    </p>
    <div style="display: flex;flex-flow: wrap;justify-content: center;">
      <div style="border: 5px solid #ccc;">
        <h4>你的画面</h4>
        <video id="localVideo" autoplay controls></video>
      </div>
      <div style="border: 5px solid #ccc;">
        <h4>对象画面</h4>
        <video id="remoteVideo" autoplay controls></video>
      </div>
    </div>
    
    <div id="dialog-confirm" title="接受视频通话吗?">
        <p>
          <span class="ui-icon ui-icon-info" style="float:left; margin:12px 12px 20px 0;"></span><label id="lblFrom"></label>
          打你,是否接受?
        </p>
    </div>
    <div id="tip">
      等待分享链接给对象...
    </div>
  </div>
</body>

</html>

标签:function,console,log,点对点,call,var,服务器,startId,webrtc
来源: https://www.cnblogs.com/guanchaoguo/p/16311574.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有