我一直在尝试使用.ontrack来显示远程视频流,该代码在我的代码的对等连接功能下。到目前为止,.ontrack仅在调用方触发,而在被调用方则不会触发,甚至在调用该函数时也不会触发。
检查.ontrack是否触发的日志将显示“ Got Remote Stream”,但仅在调用方显示,这可能是问题所在,但是我不确定为什么另一方不进入包含.ontrack,当它没有该语句要检查的event.stream [0]时。
我在下面添加了来自Caller和Callee的控制台日志。图片中未显示,过一会儿候选人将显示为空,但两个用户仍保持联系。
main.js
'use strict';
var isInitiator;
var configuration = {
iceServers: [
{
urls: 'stun:stun.l.google.com:19302'
}
]
};
var pc = new RTCPeerConnection(configuration);
// Define action buttons.
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
/////////////////////////////////////////////
window.room = prompt('Enter room name:');
var socket = io.connect();
if (room !== '') {
console.log('Message from client: Asking to join room ' + room);
socket.emit('create or join', room);
}
socket.on('created', function(room) {
console.log('Created room ' + room);
isInitiator = true;
startVideo();
});
socket.on('full', function(room) {
console.log('Message from client: Room ' + room + ' is full :^(');
});
socket.on('joined', function(room) {
console.log('joined: ' + room);
startVideo();
callButton.disabled = true;
});
socket.on('log', function(array) {
console.log.apply(console, array);
});
////////////////////////////////////////////////
async function sendMessage(message) {
console.log('Client sending message: ', message);
await socket.emit('message', message);
}
// This client receives a message
socket.on('message', async function(message) {
try {
if (message.type === 'offer') {
await pc.setRemoteDescription(new RTCSessionDescription(message));
await pc
.setLocalDescription(await pc.createAnswer())
.then(function() {
sendMessage(pc.localDescription);
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
createPeerConnection();
} else if (message.type === 'answer') {
await pc.setRemoteDescription(new RTCSessionDescription(message));
} else if (message.type === 'candidate') {
await pc.addIceCandidate(candidate);
}
} catch (err) {
console.error(err);
}
});
////////////////////////////////////////////////////
const localVideo = document.querySelector('#localVideo');
const remoteVideo = document.querySelector('#remoteVideo');
// Set up initial action buttons status: disable call and hangup.
callButton.disabled = true;
hangupButton.disabled = true;
// Add click event handlers for buttons.
callButton.addEventListener('click', callStart);
hangupButton.addEventListener('click', hangupCall);
function startVideo() {
navigator.mediaDevices
.getUserMedia({
audio: true,
video: true
})
.then(function(stream) {
localVideo.srcObject = stream;
stream.getTracks().forEach(track => pc.addTrack(track, stream));
})
.catch(function(err) {
console.log('getUserMedia() error: ' + err.name);
});
callButton.disabled = false;
}
async function callStart() {
createPeerConnection();
callButton.disabled = true;
hangupButton.disabled = false;
if (isInitiator) {
console.log('Sending offer to peer');
await pc
.setLocalDescription(await pc.createOffer())
.then(function() {
sendMessage(pc.localDescription);
})
.catch(function(err) {
console.log(err.name + ': ' + err.message);
});
}
}
/////////////////////////////////////////////////////////
function createPeerConnection() {
try {
pc.ontrack = event => {
if (remoteVideo.srcObject !== event.streams[0]) {
remoteVideo.srcObject = event.streams[0];
console.log('Got remote stream');
}
};
pc.onicecandidate = ({ candidate }) => sendMessage({ candidate });
console.log('Created RTCPeerConnnection');
} catch (e) {
console.log('Failed to create PeerConnection, exception: ' + e.message);
alert('Cannot create RTCPeerConnection object.');
return;
}
}
function hangupCall() {
pc.close();
pc = null;
callButton.disabled = false;
hangupButton.disabled = true;
console.log('Call Ended');
}
index.js
'use strict';
var express = require('express');
var app = (module.exports.app = express());
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
const PORT_NO = process.env.APP_PORT || 3000;
server.listen(PORT_NO);
app.get('/', function(request, response) {
response.sendFile(path.resolve('./index.html'));
});
app.use(express.static('.'));
io.on('connection', socket => {
function log() {
const array = ['Message from server:'];
for (let i = 0; i < arguments.length; i++) {
array.push(arguments[i]);
}
socket.emit('log', array);
}
socket.on('message', message => {
log('Got message:', message);
socket.broadcast.emit('message', message);
});
socket.on('create or join', room => {
var clientsInRoom = io.sockets.adapter.rooms[room];
var numClients = clientsInRoom
? Object.keys(clientsInRoom.sockets).length
: 0;
// max two clients
if (numClients === 2) {
socket.emit('full', room);
return;
}
log('Room ' + room + ' now has ' + (numClients + 1) + ' client(s)');
if (numClients === 0) {
socket.join(room);
log('Client ID ' + socket.id + ' created room ' + room);
socket.emit('created', room, socket.id);
} else {
log('Client ID ' + socket.id + ' joined room ' + room);
io.sockets.in(room).emit('join', room);
socket.join(room);
socket.emit('joined', room, socket.id);
io.sockets.in(room).emit('ready');
}
});
});
答案 0 :(得分:0)
让加入者成为发起者。
我猜'created'
发生在'joined'
之前?即一方在第二方加入之前创建房间?
由于您的startVideo()
所做的不只是开始本地视频,它实际上开始了连接协商,因此我怀疑您在第二方准备就绪之前就开始进行比赛。而是尝试:
socket.on('created', function(room) {
console.log('Created room ' + room);
startVideo();
});
socket.on('joined', function(room) {
console.log('joined: ' + room);
isInitiator = true; // <-- begin negotiating once 2nd party arrives.
startVideo();
});
答案 1 :(得分:0)
您在答录器侧缺少对createPeerConnection()
的呼叫,这意味着答录器未正确设置为向ICE候选人发送信号或触发跟踪事件。
您只能从startCall()
进行呼叫,因此只有在几乎完全同时按下两端的通话按钮时,此方法才起作用。
createPeerConnection()
是用词不当。相反,只需在页面加载时使用pc
和ontrack
回调来初始化onicecandidate
。
您向我们展示的与WebRTC相关的其余代码看起来都不错-除非您在答录器端两次致电getUserMedia
,这是多余的,但这不成问题。
我怀疑您的服务器逻辑中存在错误。例如。您并没有向我们展示发出'create or join'
会如何变成'created'
或'joined'
套接字消息。您还试图预先确定要约/答案交换中的哪一方,这很好,除非这意味着您在应答方上的Call
按钮不起作用。大多数演示程序只会让任何人只要按一下按钮就可以成为要约人,尽管这可能会引起眩光。仅供参考。
此外,您在这里有一个双向呼叫,可以在两个方向上发送视频,但您没有提到您没有看到的 远程视频。>
有关工作示例,请查看我的two-way tab demo。在同一浏览器中的两个相邻窗口中将其打开,然后在其中的一个中单击Call
按钮以进行连接。您应该看到(相同)双向发送的视频。它依赖于使用localStorage的localSocket
黑客。