WebRTC支持用于语音呼叫、视频聊天和 P2P 文件共享的浏览器到浏览器应用程序。
WebRTC 可用于 Chrome、Opera 和 Firefox等主流浏览器。Web RTC 实现了三个 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);
屏幕截图
它也可以在带有 mediaStreamSource 的 Chrome 浏览器中使用,并且它需要 HTTPS。此功能在Opera中尚不可用。
会话控制、网络和媒体信息
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));
};
参考:https://www.tutorialspoint.com/html5/html5_web_rtc.htm
版权声明:本文内容转自互联网,本文观点仅代表作者本人。本站仅提供信息存储空间服务,所有权归原作者所有。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至1393616908@qq.com 举报,一经查实,本站将立刻删除。