我正在尝试使用收发器在两个对等点之间建立 WebRTC 连接来管理音频流。我有一个场景,我希望每个对等点都有一个具有 sendrecv 方向的收发器。但是,当我运行以下代码时,我观察到 RemoteConnection 最终有两个收发器:一个带有 null 中值的 sendrecv 收发器和一个附加的 recvonly 收发器。
这是我正在使用的代码:
<!DOCTYPE html>
<html>
<body>
<h2>WebRTC with Transceivers on Both Peers</h2>
<button onclick="startConnection()">Start Connection</button>
<script>
let localConnection;
let remoteConnection;
let localStream;
let remoteStream;
async function startConnection() {
// Step 1: Get audio from user's microphone for the local peer
localStream = await navigator.mediaDevices.getUserMedia({ audio: true });
// Step 2: Create local and remote peer connections
localConnection = new RTCPeerConnection();
remoteConnection = new RTCPeerConnection();
// Step 3: Handle ICE candidates for both peers
localConnection.onicecandidate = (e) => {
if (e.candidate) remoteConnection.addIceCandidate(e.candidate);
};
remoteConnection.onicecandidate = (e) => {
if (e.candidate) localConnection.addIceCandidate(e.candidate);
};
// Step 4: Create transceivers on both peers
// Local peer adds audio transceiver with 'sendrecv' direction
const localTransceiver = localConnection.addTransceiver('audio', {
direction: 'sendrecv',
});
localTransceiver.sender.replaceTrack(localStream.getAudioTracks()[0]);
// Remote peer also adds a transceiver for symmetry
const remoteTransceiver = remoteConnection.addTransceiver('audio', { direction: 'sendrecv' });
remoteTransceiver.sender.replaceTrack(localStream.getAudioTracks()[0]);
// Step 5: Handle remote stream received on the remote peer
remoteStream = new MediaStream();
remoteConnection.ontrack = (event) => {
remoteStream.addTrack(event.track);
console.log('Received remote audio track');
// Attach remoteStream to an audio element to play the received audio
const remoteAudio = document.createElement('audio');
remoteAudio.srcObject = remoteStream;
remoteAudio.autoplay = true;
document.body.appendChild(remoteAudio);
};
const offerj = await remoteConnection.createOffer();
await remoteConnection.setLocalDescription(offerj);
// Step 6: Start the offer/answer negotiation process
const offer = await localConnection.createOffer();
await localConnection.setLocalDescription(offer);
await remoteConnection.setRemoteDescription(offer);
const answer = await remoteConnection.createAnswer();
await remoteConnection.setLocalDescription(answer);
await localConnection.setRemoteDescription(answer);
console.log(localConnection.getTransceivers())
console.log(remoteConnection.getTransceivers())
console.log('WebRTC connection established with transceivers on both sides.');
}
</script>
</body>
</html>
观察: 运行代码后,我希望在 localConnection 和 RemoteConnection 上看到一个 sendrecv 收发器。 相反,remoteConnection 最终有两个收发器:
问题:
预期行为: 我希望双方都拥有一个 sendrecv 收发器,使他们能够无缝发送和接收音频。
任何解决此问题的见解或建议将不胜感激!
这按预期工作,addTransceiver 显式创建一个收发器,而不与 addTrack 完成的 setRemoteDescription 中的匹配。
您创建的接收器收发器只能在远程端发起的第二次协商中使用。