WebRTC,名称源自网页实时通信(Web Real-Time Communication)的缩写,是一个支持网页浏览器进行实时语音对话或视频对话的技术。WebRTC实现了基于网页的视频会议,标准是WHATWG 协议,目的是通过浏览器提供简单的javascript就可以达到实时通讯(Real-Time Communications (RTC))能力。

WebRTC主要包括三个API接口:

  • getUserMedia
  • RTCPeerConnection
  • RTCDataChannel

1.getUserMedia

getUserMedia主要用于获取本地的音频和视频流

getUserMedia(streams, success, error);

streams 选项对象,比如{audio:true, video:true}
success 成功后的回调函数
error   失败后的回调函数

调用摄像头的实例

<video id='localVideo' autoplay muted controls style="width: 320px; height: 240px; border: 1px solid black;">
</video>
//多浏览器支持
navigator.getUserMedia || (navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia);

//指定视频播放区域
var localVideo = document.getElementById('localVideo');

//检测浏览器是否支持getUserMedia
if (navigator.getUserMedia) {
  navigator.getUserMedia({
    video: true,
    audio: true
  }, onSuccess, onError);
} else {
  alert('getUserMedia is not supported in this browser.');
}
 
function onSuccess(stream) {
  localVideo.src = window.URL.createObjectURL(stream);
  localVideo.play();
}
 
function onError() {
  alert('There has been a problem retrieving the streams - did you allow access?');
}

这里只是调用摄像头,但在这个基础上能做许多应用,比如拍照, ascii-camera, Webcam Toy等。如果想做一个无声的监视功能,也可以参考下这篇博客Pushing HTML5 Video content over ColdFusion WebSockets

参考:

  • http://www.html5rocks.com/en/tutorials/webrtc/basics
  • http://www.creativebloq.com/javascript/get-started-webrtc-1132857
  • http://bloggeek.me/multipoint-webrtc-intro
  • http://dev.w3.org/2011/webrtc/editor/webrtc-20111004.html
  • https://dvcs.w3.org/hg/audio/raw-file/tip/streams/StreamProcessing.html
  • http://blog.gingertech.net/2013/02/06/video-conferencing-in-html5-webrtc-via-socket-io/