WebRTC عمل تطبيق باستخدام البلاك جاك ومكالمات الفيديو

عزيزي القارئ ، قبل أن نبدأ في كتابة الرمز ، لنلقي نظرة على مفهوم مكالمات الفيديو.

تخيل الموقف: لدينا منصة دردشة ونحتاج إلى ربط مكالمات الفيديو بها ، أي أن Vasya معينة يجلس على الإنترنت ويريد الاتصال بـ Petya ، لتنفيذ مثل هذه الميزة ، نحتاج إلى تقنية WebSocket .

حسنًا ، دعنا نرفع خادم WebSocket ، سيساعدنا node.js في ذلك ؛
أنشئ ملف sockets.js واكتب كود مقبس الخادم هناك:

const WebSocketServer = require('websocket').server;
const http = require('http');

const server = http.createServer(function(request, response) {
 //    ,    ,  http
});
server.listen(1337, function() {});

//   
const wsServer = new WebSocketServer({
  httpServer: server
});

wsServer.on('request', function(request) {
  let connection = request.accept(null, request.origin);
//   
})

أنشئ ملف index.html واكتب الرمز هناك لفتح اتصال مأخذ:

     <video autoplay muted height='300' width='300' style="position:fixed;bottom:0;left:0;z-index: 9999;" src="" id='my'>
          </video> <!--   --> 

          <video autoplay height='300' width='300' style="position:fixed;bottom:0;left:300px;z-index: 999999;" src="" id='not_my'>
          </video> <!--  -->

الآن قم بإنشاء وربط ملف script.js بملف html الخاص بنا:

  let connection = new WebSocket('ws://127.0.0.1:1337');//   -
  connection.onopen = function(){
//  ,  -      
 }
connection.onmessage = function(message){
//        


}
connection.onerror = function (error) {
        console.error(error)
       //  ,   
      };

لذا ، عد إلى Vasya و Petya


صورة

هذه هي المرحلة الأولية التي يتبادل فيها Vasya و Petya ببساطة JSON حول ما إذا كنا سنستقبل مكالمة أم لا.

  1. نرسل أولاً خوذة إلى مقبس خادم JSON حتى نرغب في استدعاء Petya من حساب Vasya

    connection.send(JSON.stringify({
    //  
    }))
    
  2. يجب أن نقبل JSON هذا على خادم المقبس ، بعد أن نتلقى الطلب ، نرفق حدث الرسالة بخادمنا :

    connection.on('message',function(message){
    //   message    ,     JSON  JS
    let self = JSON.parse(message.utf8Data);
    })
    

بعد أن تحدثت وقررت أن كلا المستخدمين جاهزان للمحادثة ، نحتاج إلى معرفة كيفية عمل اتصال الفيديو في متصفح ، تم إنشاء وحدة لهذا في js - RTCPeerConnection


صورة

نحتاج إلى فتح RTCPeerConnection ، الذي يمكننا من خلاله إنشاء عرض وإرساله إلى المستخدم الذي نحتاج إليه ، مرة أخرى من خلال خادم مأخذ التوصيل الخاص بنا ، والذي ، عند استلامه ، سيولد استجابة ويرسلها مرة أخرى ، وبعد ذلك نبدأ في تبادل حزم الثلج التي تحتوي على معلومات حول البيئة هذا الكمبيوتر ، وهو ضروري للنجاح في إنشاء اتصالات الفيديو.

نحن نولد ونرسل العرض


var pc = new RTCPeerConnection();
            
            var peerConnectionConfig = {
              iceServers: [
                  {
                      urls: 'stun:stun.l.google.com:19302'
                  }
                ]
            }
            pc.onicecandidate = function (event) {
              console.log('new ice candidate', event.candidate);

              if (event.candidate !== null) {
                connection.send(JSON.stringify({
                 // json  ice 
                }))
              }
          };

            navigator.getUserMedia = navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia;
                      

            navigator.getUserMedia({video: true,audio:true}, function(stream) {
              //      onaddstream  ,
              //    .
            var my_video = document.getElementById('my')
            my_video.srcObject = stream

              pc.onaddstream = e => {
                document.getElementById('not_my').srcObject = e.stream;
                console.log('not stream is added')
              }
              pc.addStream(stream);   
            
              pc.createOffer(function(offer) {
                pc.setLocalDescription(offer, function() {
                  //  offer  
                  }))
                }, e=> console.log(e));
              }, e=> console.log(e));
            },function (){console.warn("Error getting audio stream from getUserMedia")});

            //  
            function endCall() {
              var videos = document.getElementsByTagName("video");
              for (var i = 0; i < videos.length; i++) {
                videos[i].pause();
              }
            
              pc.close();
            }

            function error(err) {
              endCall();
            }
 

نعالج العرض ونولد الجواب


var pc = new RTCPeerConnection();// connection
var peerConnectionConfig = { // ice server
              iceServers: [
                  {
                      urls: 'stun:stun.l.google.com:19302'
                  }
                ]
            }
            pc.onicecandidate = function (event) {
              console.log('new ice candidate', event.candidate);

              if (event.candidate !== null) {
                // ice 
              }
          };


            navigator.getUserMedia = navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia;

            navigator.getUserMedia({video: true,audio:true}, function(stream) {//          
              var my_video = document.getElementById('my')
              my_video.srcObject = stream
              console.log('stream is added while offering')

              pc.onaddstream = e => {
                console.log('not my stream is added while offering')
                document.getElementById('not_my').srcObject = e.stream;
                
              }
              pc.addStream(stream);
            
              pc.setRemoteDescription(new RTCSessionDescription(data.offer), function() {
                pc.createAnswer(function(answer) {
                  pc.setLocalDescription(answer, function() {
                    // 
                  }, e => console.log(e));
                }, e => console.log(e));
              }, e => console.log(e));
            },function (){console.warn("Error getting audio stream from getUserMedia")});
          }
        }

نحن نقبل الإجابة وننشئ دفق فيديو


pc.setRemoteDescription(new RTCSessionDescription(data.answer), function() { }, error);

وآخر شيء يتعين علينا القيام به هو معالجة أكياس الثلج


pc.addIceCandidate(new RTCIceCandidate(ice))// ice -  ,    

All Articles