1、概述
WebRTC是“網絡實時通信”(Web Real Time Communication)的縮寫,它主要用來讓瀏覽器實時獲取和交換視頻、音頻和數據。
WebRTC共分三個API。
- MediaStream(又稱getUserMedia)
- RTCPeerConnection
- RTCDataChannel
getUserMedia主要用於獲取視頻和音頻信息,后兩個API用於瀏覽器之間的數據交換。
2、getUserMedia
2.1 簡介
首先,檢查瀏覽器是否支持getUserMedia方法。
navigator.getUserMedia ||
(navigator.getUserMedia = navigator.mozGetUserMedia || navigator.webkitGetUserMedia || navigator.msGetUserMedia);
if (navigator.getUserMedia) {
//do something
} else {
console.log('your browser not support getUserMedia');
}
Chrome21、Opera 18和Firefox 17支持該方法,目前IE還不支持,上面代碼中的msGetUserMedia只是為了確保將來的兼容。
getUserMedia方法接受三個參數。
getUserMedia(streams, success, error);
含義如下:
- streams:表示包括哪些多媒體設備的對象
- success:回調函數,獲取多媒體設備成功時調用
- error:回調函數,獲取多媒體設備失敗時調用
用法如下:
navigator.getUserMedia({
video: true,
audio: true
}, onSuccess, onError);
上面的代碼用來獲取攝像頭和麥克風的實時信息。
如果網頁使用了getUserMedia,瀏覽器就會詢問用戶,是否許可提供信息。如果用戶拒絕,就調用回調函數onError。
發生錯誤時,回調函數的參數是一個Error對象,它有一個code參數,取值如下:
- PERMISSION_DENIED:用戶拒絕提供信息。
- NOT_SUPPORTED_ERROR:瀏覽器不支持指定的媒體類型。
- MANDATORY_UNSATISHIED_ERROR:指定的媒體類型未收到媒體流。
2.2 展示攝像頭圖像
將用戶的攝像頭拍攝的圖像展示在網頁上,需要先在網頁上放置一個video元素。圖像就展示在這個元素中。
<video id="webcam"></video>
然后,用代碼獲取這個元素。
function onSuccess(stream) {
var video = document.getElementById('webcam');
//more code
}
最后,將這個元素的src屬性綁定數據流,攝像頭拍攝的圖像就可以顯示了。
function onSuccess(stream) {
var video = document.getElementById('webcam');
if (window.URL) {
video.src = window.URL.createObjectURL(stream);
} else {
video.src = stream;
}
video.autoplay = true;
//or video.play();
}
它的主要用途是讓用戶使用攝像頭為自己拍照。
2.3 捕獲麥克風聲音
通過瀏覽器捕獲聲音,相對復雜,需要借助Web Audio API。
function onSuccess(stream) {
//創建一個音頻環境對像
audioContext = window.AudioContext || window.webkitAudioContext;
context = new audioContext();
//將聲音輸入這個對像
audioInput = context.createMediaStreamSources(stream);
//設置音量節點
volume = context.createGain();
audioInput.connect(volume);
//創建緩存,用來緩存聲音
var bufferSize = 2048;
// 創建聲音的緩存節點,createJavaScriptNode方法的
// 第二個和第三個參數指的是輸入和輸出都是雙聲道。
recorder = context.createJavaScriptNode(bufferSize, 2, 2);
// 錄音過程的回調函數,基本上是將左右兩聲道的聲音
// 分別放入緩存。
recorder.onaudioprocess = function(e){
console.log('recording');
var left = e.inputBuffer.getChannelData(0);
var right = e.inputBuffer.getChannelData(1);
// we clone the samples
leftchannel.push(new Float32Array(left));
rightchannel.push(new Float32Array(right));
recordingLength += bufferSize;
}
// 將音量節點連上緩存節點,換言之,音量節點是輸入
// 和輸出的中間環節。
volume.connect(recorder);
// 將緩存節點連上輸出的目的地,可以是擴音器,也可以
// 是音頻文件。
recorder.connect(context.destination);
}
3、實時數據交換
WebRTC的另外兩個API,RTCPeerConnection用於瀏覽器之間點對點的連接,RTCDataChannel用於點對點的數據通信。
RTCPeerConnection帶有瀏覽器前綴,Chrome瀏覽器中為webkitRTCPeerConnection,Firefox瀏覽器中為mozRTCPeerConnection。Google維護一個函數庫adapter.js,用來抽像掉瀏覽器之間的差異。
var dataChannelOptions = {
ordered: false, // do not guarantee order
maxRetransmitTime: 3000, // in milliseconds
};
var peerConnection = new RTCPeerConnection();
// Establish your peer connection using your signaling channel here
var dataChannel =
peerConnection.createDataChannel("myLabel", dataChannelOptions);
dataChannel.onerror = function (error) {
console.log("Data Channel Error:", error);
};
dataChannel.onmessage = function (event) {
console.log("Got Data Channel Message:", event.data);
};
dataChannel.onopen = function () {
dataChannel.send("Hello World!");
};
dataChannel.onclose = function () {
console.log("The Data Channel is Closed");
};
4、參考鏈接
[1] Andi Smith, Get Started with WebRTC
[2] Thibault Imbert, From microphone to .WAV with: getUserMedia and Web Audio
[3] Ian Devlin, Using the getUserMedia API with the HTML5 video and canvas elements
[4] Eric Bidelman, Capturing Audio & Video in HTML5
[5] Sam Dutton, Getting Started with WebRTC
[6] Dan Ristic, WebRTC data channels
[7] Ruanyf, WebRTC
轉自http://www.4u4v.net/html5-xin-te-xing-zhi-webrtc-yin-shi-pin-shu-ju-jiao-hu.html

