在前面的章节中,已经对WebRTC相关的主要知识点举行了先容,包罗涉及的 *** 协议、会话形貌协议、若何举行 *** 穿透等,剩下的就是WebRTC的API了。
WebRTC通讯相关的API异常多,主要完成了如下功效:
相关API太多,为制止篇幅过长,文中部门接纳了伪代码举行解说。详细代码参考文章末尾,也可以在笔者的Github上找到,有问题迎接留言交流。
信令交流是WebRTC通讯中的关键环节,交流的信息包罗编解码器、 *** 协议、候选地址等。对于若何举行信令交流,WebRTC并没有明确说明,而是交给应用自己来决议,好比可以接纳WebSocket。
发送方伪代码如下:
const pc = new RTCPeerConnection(iceConfig); const offer = await pc.createOffer(); await pc.setLocalDescription(offer); sendToPeerViaSignalingServer(SIGNALING_OFFER, offer); // 发送方发送信令新闻
吸收方伪代码如下:
const pc = new RTCPeerConnection(iceConfig); await pc.setRemoteDescription(offer); const answer = await pc.createAnswer(); await pc.setLocalDescription(answer); sendToPeerViaSignalingServer(SIGNALING_ANSWER, answer); // 吸收方发送信令新闻
当内陆设置了会话形貌信息,并添加了媒体流的情况下,ICE框架就会更先 *** 候选地址。双方 *** 到候选地址后,需要交流候选地址,并从中知道合适的候选地址对。
候选地址的交流,同样接纳前面提到的信令服务,伪代码如下:
// 设置内陆会话形貌信息 const localPeer = new RTCPeerConnection(iceConfig); const offer = await pc.createOffer(); await localPeer.setLocalDescription(offer); // 内陆采集音视频 const localVideo = document.getElementById('local-video'); const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); localVideo.srcObject = mediaStream; // 添加音视频流 mediaStream.getTracks().forEach(track => { localPeer.addTrack(track, mediaStream); }); // 交流候选地址 localPeer.onicecandidate = function(evt) { if (evt.candidate) { sendToPeerViaSignalingServer(SIGNALING_CANDIDATE, evt.candidate); } }
可以使用浏览器提供的getUserMedia接口,采集内陆的音视频。
const localVideo = document.getElementById('local-video'); const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); localVideo.srcObject = mediaStream;
将采集到的音视频轨道,通过addTrack举行添加,发送给远端。
mediaStream.getTracks().forEach(track => { localPeer.addTrack(track, mediaStream); });
远端可以通过监听ontrack来监听音视频的到达,并举行播放。
remotePeer.ontrack = function(evt) { const remoteVideo = document.getElementById('remote-video'); remoteVideo.srcObject = evt.streams[0]; }
包罗两部门:客户端代码、服务端代码。
1、客户端代码
const socket = io.connect('http://localhost:3000'); const CLIENT_RTC_EVENT = 'CLIENT_RTC_EVENT'; const SERVER_RTC_EVENT = 'SERVER_RTC_EVENT'; const CLIENT_USER_EVENT = 'CLIENT_USER_EVENT'; const SERVER_USER_EVENT = 'SERVER_USER_EVENT'; const CLIENT_USER_EVENT_LOGIN = 'CLIENT_USER_EVENT_LOGIN'; // 登录 const SERVER_USER_EVENT_UPDATE_USERS = 'SERVER_USER_EVENT_UPDATE_USERS'; const SIGNALING_OFFER = 'SIGNALING_OFFER'; const SIGNALING_ANSWER = 'SIGNALING_ANSWER'; const SIGNALING_CANDIDATE = 'SIGNALING_CANDIDATE'; let remoteUser = ''; // 远端用户 let localUser = ''; // 内陆登录用户 function log(msg) { console.log(`[client] ${msg}`); } socket.on('connect', function() { log('ws connect.'); }); socket.on('connect_error', function() { log('ws connect_error.'); }); socket.on('error', function(errorMessage) { log('ws error, ' + errorMessage); }); socket.on(SERVER_USER_EVENT, function(msg) { const type = msg.type; const payload = msg.payload; switch(type) { case SERVER_USER_EVENT_UPDATE_USERS: updateUserList(payload); break; } log(`[${SERVER_USER_EVENT}] [${type}], ${ *** ON.stringify(msg)}`); }); socket.on(SERVER_RTC_EVENT, function(msg) { const {type} = msg; switch(type) { case SIGNALING_OFFER: handleReceiveOffer(msg); break; case SIGNALING_ANSWER: handleReceiveAnswer(msg); break; case SIGNALING_CANDIDATE: handleReceiveCandidate(msg); break; } }); async function handleReceiveOffer(msg) { log(`receive remote description from ${msg.payload.from}`); // 设置远端形貌 const remoteDescription = new RTCSessionDescription(msg.payload.sdp); remoteUser = msg.payload.from; createPeerConnection(); await pc.setRemoteDescription(remoteDescription); // TODO 错误处置 // 内陆音视频采集 const localVideo = document.getElementById('local-video'); const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); localVideo.srcObject = mediaStream; mediaStream.getTracks().forEach(track => { pc.addTrack(track, mediaStream); // pc.addTransceiver(track, {streams: [mediaStream]}); // 这个也可以 }); // pc.addStream(mediaStream); // 现在这个也可以,不外接口后续会废弃 const answer = await pc.createAnswer(); // TODO 错误处置 await pc.setLocalDescription(answer); sendRTCEvent({ type: SIGNALING_ANSWER, payload: { sdp: answer, from: localUser, target: remoteUser } }); } async function handleReceiveAnswer(msg) { log(`receive remote answer from ${msg.payload.from}`); const remoteDescription = new RTCSessionDescription(msg.payload.sdp); remoteUser = msg.payload.from; await pc.setRemoteDescription(remoteDescription); // TODO 错误处置 } async function handleReceiveCandidate(msg){ log(`receive candidate from ${msg.payload.from}`); await pc.addIceCandidate(msg.payload.candidate); // TODO 错误处置 } /** * 发送用户相关新闻给服务器 * @param {Object} msg 花样如 { type: 'xx', payload: {} } */ function sendUserEvent(msg) { socket.emit(CLIENT_USER_EVENT, *** ON.stringify(msg)); } /** * 发送RTC相关新闻给服务器 * @param {Object} msg 花样如{ type: 'xx', payload: {} } */ function sendRTCEvent(msg) { socket.emit(CLIENT_RTC_EVENT, *** ON.stringify(msg)); } let pc = null; /** * 约请用户加入视频谈天 * 1、内陆启动视频采集 * 2、交流信令 */ async function startVideoTalk() { // 开启内陆视频 const localVideo = document.getElementById('local-video'); const mediaStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }); localVideo.srcObject = mediaStream; // 建立 peerConnection createPeerConnection(); // 将媒体流添加到webrtc的音视频收发器 mediaStream.getTracks().forEach(track => { pc.addTrack(track, mediaStream); // pc.addTransceiver(track, {streams: [mediaStream]}); }); // pc.addStream(mediaStream); // 现在这个也可以,不外接口后续会废弃 } function createPeerConnection() { const iceConfig = {"iceServers": [ {url: 'stun:stun.ekiga.net'}, {url: 'turn:turnserver.com', username: 'user', credential: 'pass'} ]}; pc = new RTCPeerConnection(iceConfig); pc.onnegotiationneeded = onnegotiationneeded; pc.onicecandidate = onicecandidate; pc.onicegatheringstatechange = onicegatheringstatechange; pc.oniceconnectionstatechange = oniceconnectionstatechange; pc.onsignalingstatechange = onsignalingstatechange; pc.ontrack = ontrack; return pc; } async function onnegotiationneeded() { log(`onnegotiationneeded.`); const offer = await pc.createOffer(); await pc.setLocalDescription(offer); // TODO 错误处置 sendRTCEvent({ type: SIGNALING_OFFER, payload: { from: localUser, target: remoteUser, sdp: pc.localDescription // TODO 直接用offer? } }); } function onicecandidate(evt) { if (evt.candidate) { log(`onicecandidate.`); sendRTCEvent({ type: SIGNALING_CANDIDATE, payload: { from: localUser, target: remoteUser, candidate: evt.candidate } }); } } function onicegatheringstatechange(evt) { log(`onicegatheringstatechange, pc.iceGatheringState is ${pc.iceGatheringState}.`); } function oniceconnectionstatechange(evt) { log(`oniceconnectionstatechange, pc.iceConnectionState is ${pc.iceConnectionState}.`); } function onsignalingstatechange(evt) { log(`onsignalingstatechange, pc.signalingstate is ${pc.signalingstate}.`); } // 挪用 pc.addTrack(track, mediaStream),remote peer的 onTrack 会触发两次 // 实际上两次触发时,evt.streams[0] 指向同一个mediaStream引用 // 这个行为有点新鲜,github issue 也有提到 https://github.com/meetecho/janus-gateway/issues/1313 let stream; function ontrack(evt) { // if (!stream) { // stream = evt.streams[0]; // } else { // console.log(`${stream === evt.streams[0]}`); // 这里为true // } log(`ontrack.`); const remoteVideo = document.getElementById('remote-video'); remoteVideo.srcObject = evt.streams[0]; } // 点击用户列表 async function handleUserClick(evt) { const target = evt.target; const userName = target.getAttribute('data-name').trim(); if (userName === localUser) { alert('不能跟自己举行视频会话'); return; } log(`online user selected: ${userName}`); remoteUser = userName; await startVideoTalk(remoteUser); } /** * 更新用户列表 * @param {Array} users 用户列表,好比 [{name: '小明', name: '小强'}] */ function updateUserList(users) { const fragment = document.createDocumentFragment(); const userList = document.getElementById('login-users'); userList.innerHTML = ''; users.forEach(user => { const li = document.createElement('li'); li.innerHTML = user.userName; li.setAttribute('data-name', user.userName); li.addEventListener('click', handleUserClick); fragment.appendChild(li); }); userList.appendChild(fragment); } /** * 用户登录 * @param {String} loginName 用户名 */ function login(loginName) { localUser = loginName; sendUserEvent({ type: CLIENT_USER_EVENT_LOGIN, payload: { loginName: loginName } }); } // 处置登录 function handleLogin(evt) { let loginName = document.getElementById('login-name').value.trim(); if (loginName === '') { alert('用户名为空!'); return; } login(loginName); } function init() { document.getElementById('login-btn').addEventListener('click', handleLogin); } init();
2、服务端代码
// 添加ws服务 const io = require('socket.io')(server); let connectionList = []; const CLIENT_RTC_EVENT = 'CLIENT_RTC_EVENT'; const SERVER_RTC_EVENT = 'SERVER_RTC_EVENT'; const CLIENT_USER_EVENT = 'CLIENT_USER_EVENT'; const SERVER_USER_EVENT = 'SERVER_USER_EVENT'; const CLIENT_USER_EVENT_LOGIN = 'CLIENT_USER_EVENT_LOGIN'; const SERVER_USER_EVENT_UPDATE_USERS = 'SERVER_USER_EVENT_UPDATE_USERS'; function getOnlineUser() { return connectionList .filter(item => { return item.userName !== ''; }) .map(item => { return { userName: item.userName }; }); } function setUserName(connection, userName) { connectionList.forEach(item => { if (item.connection.id === connection.id) { item.userName = userName; } }); } function updateUsers(connection) { connection.emit(SERVER_USER_EVENT, { type: SERVER_USER_EVENT_UPDATE_USERS, payload: getOnlineUser()}); } io.on('connection', function (connection) { connectionList.push({ connection: connection, userName: '' }); // 连接上的用户,推送在线用户列表 // connection.emit(SERVER_USER_EVENT, { type: SERVER_USER_EVENT_UPDATE_USERS, payload: getOnlineUser()}); updateUsers(connection); connection.on(CLIENT_USER_EVENT, function(jsonString) { const msg = *** ON.parse(jsonString); const {type, payload} = msg; if (type === CLIENT_USER_EVENT_LOGIN) { setUserName(connection, payload.loginName); connectionList.forEach(item => { // item.connection.emit(SERVER_USER_EVENT, { type: SERVER_USER_EVENT_UPDATE_USERS, payload: getOnlineUser()}); updateUsers(item.connection); }); } }); connection.on(CLIENT_RTC_EVENT, function(jsonString) { const msg = *** ON.parse(jsonString); const {payload} = msg; const target = payload.target; const targetConn = connectionList.find(item => { return item.userName === target; }); if (targetConn) { targetConn.connection.emit(SERVER_RTC_EVENT, msg); } }); connection.on('disconnect', function () { connectionList = connectionList.filter(item => { return item.connection.id !== connection.id; }); connectionList.forEach(item => { // item.connection.emit(SERVER_USER_EVENT, { type: SERVER_USER_EVENT_UPDATE_USERS, payload: getOnlineUser()}); updateUsers(item.connection); }); }); });
WebRTC的API异常多,由于WebRTC自己就比较复杂,随着时间的推移,WebRTC的某些API(包罗某些协议细节)也在改动或被废弃,这其中也有向后兼容带来的复杂性,好比内陆视频采集后加入传输流,可以接纳 addStream 或 addTrack 或 addTransceiver,再好比会话形貌版本从plan-b迁移到unified-plan。
建议亲自动手撸一遍代码,加深领会。
2019.08.02-video-talk-using-webrtc
https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection
onremotestream called twice for each remote stream
原文:https://segmentfault.com/a/1190000019970102
1.阿里云: 本站现在使用的是阿里云主机,平安/可靠/稳固。点击领取2000米代金券、领会最新阿里云产物的种种优惠流动点击进入
央视网消息:面对严峻复杂的疫情防控形势,各地纷纷倡导就地过年,而就地过年政策是分级分类的,中高风险地区严格执行相关规定,低风险地区倡导就地过年,非必要不出行。过去,有些地方为降低防控风险、减轻防控...
直面产业互联网在目标对象、互联网角色、商业模式等方面的特殊性,从特殊性着手,我们才能找到产业互联网时代的正确发展之路。 相对于用新的方式和方法继续挖掘C端用户本身的消费潜能,以B端用户为对象的发展方...
最近很多同学都开始论文查重了,不过都比较担心什么呢?第一是准确度,第二就是会不会泄露论文了,今天小编就带大家看看大雅论文怎么样,大雅查重会泄露论文吗?看看他与知网查重的却别在哪里,下面就来看看吧!...
寸功未立,终究還是要做打扫那样的低贱的活计上海酒店模特预约,从一场风雪交加中登场,最后,又在一场风雪交加中迈向身亡,严寒与冰冷随着了艾格尔的一生。 女学妹山枫简单自我介绍 能跟大伙儿沟通交流就是我三生...
苏州商务陪伴小学妹极品空姐经纪人安全吗【严光兰】 今天给大家分享的内容是“苏州商务陪伴小学妹极品空姐经纪人安全吗【严光兰】”,我是严光兰,来自青海省,今年30岁,作为职业:广州高端伴游,我热爱我的职业...
安全问题是每个电脑用户时时刻刻需要注意的问题。这个计算机发达的时代,一个很不起眼的小病毒就可以轻松把整个系统搞垮,甚至泄露你的信息。 随着安全化的升级,我们眼中的安全问题也不仅仅是杀毒这么简单了,清...