WebRTC简介

2017-12-19  本文已影响19人  霜之幽语

Three main tasks

Three main JavaScript APIs

MediaStream
var constraints = {video: true};

function successCallback(stream) {
  var video = document.querySelector("video");
  video.src = window.URL.createObjectURL(stream);
}

function errorCallback(error) {
  console.log("navigator.getUserMedia error: ", error);
}

navigator.getUserMedia(constraints, successCallback, errorCallback);

Sample
http://www.simpl.info/gum
http://idevelop.github.io/ascii-camera/
http://www.shinydemos.com/facekat/
http://webcamtoy.com/app

constraints

video: {
  mandatory: {
    minWidth: 640,
    minHeight: 360  
  },
  optional  [{
    minWidth: 1280,
    minHeight: 720
  }]
}

sample
https://simpl.info/getusermedia/constraints/

getUserMedia + Web Audio

// Success callback when requesting audio input stream
function gotStream(stream) {
  var audioContext = new webkitAudioContext();

  // Create an AudioNode from the stream
  var mediaStreamSource = audioContext.createMediaStreamSource(stream);

  // Connect it to the destination or any other node for processing!
  mediaStreamSource.connect(audioContext.destination);
}

navigator.webkitGetUserMedia({audio:true}, gotStream);

Make sure to enable Web Audio Input in about:flags!
Sample
http://www.webaudiodemos.appspot.com/AudioRecorder/index.html

gUM screencapture

var constraints = {
  video: {
    mandatory: {
      chromeMediaSource: 'screen'
    }  
  }
};

navigator.webkitGetUserMedia(constraints, gotStream);

Sample
https://html5-demos.appspot.com/static/getusermedia/screenshare.html

RTCPeerConnection
Audio and video communication between peers

RTCPeerConnection does a lot

pc = new RTCPeerConnection(null);
pc.onaddstream = gotRemoteStream;
pc.addStream(localStream);
pc.createOffer(gotOffer);

function gotOffer(desc) {
  pc.setLocalDescription(desc);
  sendOffer(desc);
}

function gotAnswer(desc) {
  pc.setRemoteDescription(desc);
}

function gotRemoteStream(e) {
  attachMediaStream(remoteVideo, e.stream);
}

Sample
http://www.simpl.info/pc

RTCDataChannel
Bidirectional communication of arbitrary data between peers

RTCDataChannel

var pc = new webkitRTCPeerConnection(servers, {optional: [{RtpDataChannels: true}]});

pc.ondatachannel = function(event) {
  receiveChannel = event.channel;
  receiveChannel.onmessage = function(event) {
    document.querySelector("div#receive").innerHTML = event.data;
  }
};

sendChannel = pc.createDataChannel("sendDataChannel", {reliabel: false});

document.querySelector("button#send").onclick = function () {
  var data = document.querySelector("textarea#send").value;
  sendChannel.send(data);
};

Sample
http://www.simpl.info/dc
http://www.sharefest.me/

上一篇 下一篇

猜你喜欢

热点阅读