亲爱的朋友们,我正在尝试构建允许将浏览器窗口连接到自身的测试应用程序(来自用户相机的条纹视频数据)。最终结果是在页面上获得两个视频流,一个直接来自相机,另一个来自浏览器在本地建立的WebRTC连接。我想问题是在实例化 RTCPeerconnection 对象时不会调用 onaddstream 方法,因此第二个屏幕不会从窗口接收 url。URL.createObjectURL(e.stream);
function hasUserMedia() {
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
return !!navigator.getUserMedia;
}
function hasRTCPeerConnection() {
window.RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
return !!window.RTCPeerConnection;
}
var yourVideo = document.querySelector('#yours'),
theirVideo = document.querySelector('#theirs'),
yourConnection, theirConnection;
if (hasUserMedia()) {
navigator.getUserMedia({ video: true, audio: false }, function (stream) {
yourVideo.src = window.URL.createObjectURL(stream);
if (hasRTCPeerConnection()) {
startPeerConnection(stream);
} else {
alert("Sorry, your browser does not support WebRTC.");
}
}, function (error) {
console.log(error);
});
} else {
alert("Sorry, your browser does not support WebRTC.");
}
function startPeerConnection(stream) {
var configuration = {
"iceServers": [{ "url": "stun:192.168.1.100:9876" }] // this is address of a local server
};
yourConnection = new mozRTCPeerConnection(configuration);
theirConnection = new mozRTCPeerConnection(configuration);
console.log(theirConnection);
// Setup stream listening
yourConnection.addStream(stream);
theirConnection.onaddstream = function (e) {
theirVideo.src = window.URL.createObjectURL(e.stream);
};
// Setup ice handling
yourConnection.onicecandidate = function (event) {
if (event.candidate) {
theirConnection.addIceCandidate(new RTCIceCandidate(event.candidate));
}
};
theirConnection.onicecandidate = function (event) {
if (event.candidate) {
yourConnection.addIceCandidate(new RTCIceCandidate(event.candidate));
}
};
// Begin the offer
yourConnection.createOffer(function (offer) {
yourConnection.setLocalDescription(offer);
theirConnection.setRemoteDescription(offer);
theirConnection.createAnswer(function (offer) {
theirConnection.setLocalDescription(offer);
yourConnection.setRemoteDescription(offer);
});
});
};
这是完整的代码: https://gist.github.com/johannesMatevosyan/8e4529fdcc53dd711479
这是它在浏览器中的外观:http://screencast.com/t/6dthclGcm
您的onaddstream
事件未触发,因为您的连接尚未启动,您必须先完成报价/应答过程,然后才能触发该事件。我在 Firefox 41.0.2 中尝试了您的代码,但由于您缺少错误回调方法而未创建报价,请尝试以下方法:
function error () { console.log('There was an error'); };
yourConnection.createOffer(function (offer) { console.log('Offer:'); console.log(offer);
yourConnection.setLocalDescription(offer);
theirConnection.setRemoteDescription(offer);
theirConnection.createAnswer(function (answer) { console.log('Answer:'); console.log(answer);
theirConnection.setLocalDescription(answer);
yourConnection.setRemoteDescription(answer);
}, error);
}, error);