当前,已经实现了使用该程序将视频从一个客户端(流媒体)传输到另一个客户端(观看者)。一切正常,直到查看器重新加载页面为止。尽管已传输流,但他的视频消失了(可以在控制台中看到)。有什么问题吗?
Streamer.js
useEffect(() => {
navigator.mediaDevices
.getUserMedia({
video: true,
audio: true,
})
.then(stream => {
// Display own video
localVideo.current.srcObject = stream;
// Stream video to attendees
gotMedia(stream);
})
.catch(error => {
console.error(error);
});
}, []);
const gotMedia = stream => {
localStream.current = stream;
broadcaster.current = new Peer({
initiator: true,
stream: localStream.current,
config: configuration,
offerConstraints: {
offerToReceiveAudio: true,
offerToReceiveVideo: true,
},
});
broadcaster.current.on('signal', data => {
socket.emit('signal', { data, room: routeMatch.params.id });
});
// destroy current peerconnection and create a new one
socket.on('startConnection', () => {
console.log('startConnection');
if (broadcaster.current) broadcaster.current.destroy();
broadcaster.current = new Peer({
initiator: true,
stream: localStream.current,
config: configuration,
offerConstraints: {
offerToReceiveAudio: true,
offerToReceiveVideo: true,
},
});
broadcaster.current.on('signal', data => {
socket.emit('signal', { data, room: routeMatch.params.id });
});
});
socket.on('signal', data => {
broadcaster.current && broadcaster.current.signal(data);
});
};
Viewer.js
useEffect(() => {
attendee.current = new Peer({
initiator: false,
config: configuration,
answerConstraints: {
offerToReceiveAudio: false,
offerToReceiveVideo: false,
},
});
attendee.current.on('signal', data => {
socket.emit('signal', { data, room: routeMatch.params.id });
});
socket.on('signal', data => {
attendee.current && attendee.current.signal(data);
});
// Get remote video stream and display it
attendee.current.on('stream', stream => {
console.log('stream', stream);
console.log('remoteVideo.current.srcObject before', remoteVideo.current.srcObject);
remoteVideo.current.srcObject = stream;
console.log('remoteVideo.current.srcObject after', remoteVideo.current.srcObject);
});
// Ask broadcaster to start his connection
socket.emit('startConnection', routeMatch.params.id);
return () => {
attendee.current.destroy();
};
}, []);
重新加载页面后,我们看到有视频流,但是由于某些原因无法播放视频(console.log('remoteVideo.current.srcObject after', remoteVideo.current.srcObject);
]
问题是,当您使用ìnitialize: true
在流媒体中初始化Peer时,它将尝试直接使用给定的设置进行连接。当您重新加载查看器时,它将不会收到任何信号,因为流式传输器一次发送了此初始化。
解决方案是,一旦查看器连接,就在流光中创建一个新的Peer对象。 (并在查看器断开连接时也删除该对象)。
这里是github project(demo),您可以以此为灵感来扩展您的项目。