HTML - WebRTC



WebRTC 由全球資訊網聯盟 (W3C) 引入,支援瀏覽器到瀏覽器的應用程式,例如語音通話、影片聊天和點對點檔案共享。

WebRTC 實現如下所示的三個 API:

  • MediaStream - 獲取使用者攝像頭和麥克風的訪問許可權。

  • RTCPeerConnection - 獲取音訊或視訊通話功能的訪問許可權。

  • RTCDataChannel - 獲取點對點通訊的訪問許可權。

MediaStream

MediaStream 代表媒體的同步流,例如,點選 HTML5 演示部分中的 HTML5 影片播放器,或者點選這裡

以上示例包含 stream.getAudioTracks() 和 stream.VideoTracks()。如果沒有音訊軌跡,它將返回一個空陣列,然後它將檢查影片流,如果網路攝像頭已連線,stream.getVideoTracks() 將返回一個包含一個 MediaStreamTrack 的陣列,該陣列表示來自網路攝像頭的流。一個簡單的例子是聊天應用程式,聊天應用程式從網路攝像頭、後置攝像頭、麥克風獲取流。

MediaStream 的示例程式碼

function gotStream(stream) {
   window.AudioContext = window.AudioContext || window.webkitAudioContext;
   var audioContext = new AudioContext();
   
   // Create an AudioNode from the stream
   var mediaStreamSource = audioContext.createMediaStreamSource(stream);
   // Connect it to destination to hear yourself
   // or any other node for processing!
   mediaStreamSource.connect(audioContext.destination);
}
navigator.getUserMedia({audio:true}, gotStream);

會話控制、網路和媒體資訊

WebRTC 需要瀏覽器之間的點對點通訊。此機制需要信令、網路資訊、會話控制和媒體資訊。Web 開發人員可以選擇不同的機制在瀏覽器之間進行通訊,例如 SIP 或 XMPP 或任何雙向通訊。

createSignalingChannel() 的示例程式碼

var signalingChannel = createSignalingChannel();
var pc;
var configuration = ...;
// run start(true) to initiate a call
function start(isCaller) {
   pc = new RTCPeerConnection(configuration);
   // send any ice candidates to the other peer
   pc.onicecandidate = function (evt) {
      signalingChannel.send(JSON.stringify({ "candidate": evt.candidate }));
   };
   // once remote stream arrives, show it in the remote video element
   pc.onaddstream = function (evt) {
      remoteView.src = URL.createObjectURL(evt.stream);
   };
   // get the local stream, show it in the local video element and send it
   navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
      selfView.src = URL.createObjectURL(stream);
      pc.addStream(stream);
      if (isCaller)
         pc.createOffer(gotDescription);
      else
         pc.createAnswer(pc.remoteDescription, gotDescription);
         function gotDescription(desc) {
            pc.setLocalDescription(desc);
            signalingChannel.send(JSON.stringify({ "sdp": desc }));
         }
      });
   }
   signalingChannel.onmessage = function (evt) {
      if (!pc)
         start(false);
         var signal = JSON.parse(evt.data);
      if (signal.sdp)
         pc.setRemoteDescription(new RTCSessionDescription(signal.sdp));
      else
         pc.addIceCandidate(new RTCIceCandidate(signal.candidate));
};
廣告