我想在react.js
和WebRTC
上进行简单的视频聊天。但在pc.addStream(localStream)
行中发生错误:
TypeError:RTCPeerConnection.addStream的参数1不是对象。
而且我不明白为什么我看不到该行中的日志:pc.onicecandidate = (e)=>{ console.log('onicecandidate');
那就是所有代码:
class App extends Component {
constructor(props) {
super(props);
}
componentDidUpdate(){
loadScript("https://webrtc.github.io/adapter/adapter-latest.js");
let localVideo, remoteVideo, peerConnection, localStream;
$('#start').on('click', ()=>{ start(true) });
let id = uuid();
localVideo = document.getElementById('localVideo');
remoteVideo = document.getElementById('remoteVideo');
if(navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia( { video:true, audio:true}).then( ( stream )=> {
localStream = stream;
localVideo.src = window.URL.createObjectURL(stream);
}).catch(errorHandler);
}else{ alert('Your browser does not support getUserMedia API'); }
function start(isCaller) {
peerConnection = new RTCPeerConnection( { 'iceServers': [{'urls': 'stun:stun.services.mozilla.com'}, {'urls': 'stun:stun.l.google.com:19302'},]});
peerConnection.onicecandidate = ( e ) => {
if(e.candidate != null) {
Meteor.call('addMsgRtc', JSON.stringify({'ice': e.candidate, '_id':id}), id);
}
};
peerConnection.onaddstream = ( e )=>{
remoteVideo.src = window.URL.createObjectURL(e.stream);
};
peerConnection.addStream(localStream);
if(isCaller) {
peerConnection.createOffer().then(
createdDescription).catch(errorHandler);
}
}
if (!this.props.loadingRtc) {
for(let i of this.props.messagesRtc){
if(!peerConnection) start(false);
let signal = JSON.parse(i.text);
if(signal._id == id) return;
if(signal.sdp) {
peerConnection.setRemoteDescription(new RTCSessionDescription(signal.sdp)).then(()=> {
if(signal.sdp.type == 'offer') { peerConnection.createAnswer().then(createdDescription).catch(errorHandler);
}
}).catch(errorHandler);
}else if(signal.ice) {
peerConnection.addIceCandidate(new RTCIceCandidate(signal.ice)).catch(errorHandler);
}
}
}
function createdDescription(description) {
peerConnection.setLocalDescription(description).then(()=> {
Meteor.call('addMsgRtc', JSON.stringify({'sdp':peerConnection.localDescription, '_id':id}), id);
}).catch(errorHandler);
}
function errorHandler(error) { console.log(error); }
}
}
render() {
return (
<div id="container">
<video id="localVideo" autoPlay muted style={{width:"40%"}}></video>
<video id="remoteVideo" autoPlay style={{width:"40%"}}></video>
<br/>
</div>
);
}
}
export default createContainer( ()=> {
const subscriptionRtc = Meteor.subscribe('rtc');
const loadingRtc = !subscriptionRtc.ready();
return {
loadingRtc:loadingRtc,
messagesRtc: msgRtc.find().fetch(),
};
}, App);
最佳答案
getUserMedia
是一个返回诺言的异步操作。调用.then()
时,尚未执行设置localStream
的pc.addStream
。
您可能需要将start()
移到.then()
中。
ontrack事件没有e.stream
btw。您可能想使用onaddstream
代替。另外,请设置srcObject = e.stream
而不是使用URL.createObjectURL
。