使用WebRTC弄湿自己并且遇到RTCPeerConnection.ontrack事件的问题,无论何时创建新的MediaStreamTrack对象(RTCPeerConnection.addTrack()函数)都不会触发。
使用教科书WebRTC getUserMedia示例,我从笔记本电脑的相机中获取单个流,当单击“开始”按钮时,我将其设置为一个元素(本地)的srcObject。单击“调用”按钮时,我在抓取的流上使用addTrack方法,该方法保存在全局localStream变量中。此时全局定义的ontrack事件处理程序应该触发并给我第二个视频,对吧?不过没有骰子。
我能够使用addStream和onaddstream - 但两者都已从最新的WebRTC规范中删除,并且最新版本的Chrome和FireFox不支持。
附带图片和脚本 - 非常感谢任何指导!
'use strict';
var localStream;
var yourVideo = document.querySelector('#yours');
var theirVideo = document.querySelector('#theirs');
var callBtn = document.querySelector('#callBtn');
var startBtn = document.querySelector('#startBtn');
startBtn.onclick = hasUserMedia;
callBtn.onclick = call;
var cfg = null;
var pc1 = new RTCPeerConnection(cfg);
var pc2 = new RTCPeerConnection(cfg);
pc1.ontrack = function(e){
console.log("ontrack fired!");
theirVideo.srcObject = e.streams[0];
}
function hasUserMedia(){
console.log("entering hasUserMedia()...");
navigator.mediaDevices.getUserMedia({video: true, audio: false}).then(function(stream){
localStream = stream;
console.log("stream val: " + localStream);
yourVideo.srcObject = stream;
});
}
function call(){
console.log("stream val @ call(): " + localStream);
localStream.getTracks().forEach(track => pc1.addTrack(track, localStream));
}
的index.html
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Learning WebRTC - Chapter 4: Creating a
RTCPeerConnection</title>
<style>
body {
background-color: #3D6DF2;
margin-top: 15px;
}
video {
background: black;
border: 1px solid gray;
}
#container {
position: relative;
display: block;
margin: 0 auto;
width: 500px;
height: 500px;
}
#yours {
width: 150px;
height: 150px;
position: absolute;
top: 15px;
right: 15px;
}
#theirs {
width: 500px;
height: 500px;
}
</style>
</head>
<body>
<div id="container">
<video id="yours" autoplay></video>
<video id="theirs" autoplay></video>
<button id="startBtn">Start</button>
<button id="callBtn">Call</button>
</div>
<script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
答案 0 :(得分:3)
Firefox和Chrome仍支持onaddstream。 Chrome还不支持addTrack,你仍然可以使用addStream(尽管Firefox抱怨)。
您的脚本缺少SDP和ICE候选人的交换,因为ontrack也会被激活。
查看https://webrtc.github.io/samples/src/content/peerconnection/pc1/以获取完整且有效的示例。
答案 1 :(得分:1)
addTrack on Chromium Issue Tracker
addTrack is blocked by RTCRtpSender and RTCRtpReceiver extensions to RTCPeerConnection
答案 2 :(得分:0)
我在尝试实施视频聊天时遇到了同样的问题,但我找到了解决办法。修复很简单;确保在创建ontrack
时添加onicecandidate
事件,rtcpeerconnection
和视频流对象。请参阅以下代码
var configuration = {
offerToReceiveAudio: true,
offerToReceiveVideo: true
}
var peerConn = new RTCPeerConnection(cofiguration);
peerConn.ontrack = gotStream;
peerConn.onicecandidate = gotIceCandidate;
peerConn.addStream(localStream);
//and do the rest your style... Hope this helps.