0

我尝试从Webrtc.org peerconnection guide实现 webrtc 代码。虽然没有生成有效的候选冰。我还注意到在 sdp 中总是使用 localhost ip (127.0.0.1),即使我在不​​同的设备上运行应用程序也是如此。在 Firefox 中,我确实收到了一个 icecandidate 事件。虽然 event.candidate == null。

有什么我做错了吗?

这是代码:

let socket = io()
let localStream = null;
const configuration = {
    'iceServers': [{
        'urls': 'stun:stun.l.google.com:19302'
    }]
}
let peerConnection = new RTCPeerConnection(configuration)

// init video media
function start() {
    navigator.mediaDevices.getUserMedia({
        audio: true,
        video: true
    }).then(stream => {
        localVideo.srcObject = stream
        localStream = stream
    })
    for (let track of localStream.getTracks()) {
        peerConnection.addTrack(track, localStream)
    }
}

// starts the call
async function call() {
    const offer = await peerConnection.createOffer()
    await peerConnection.setLocalDescription(offer)
    socket.emit('offer', offer)
}

peerConnection.onicecandidate = event => {
    if (event.candidate) {
        socket.emit('newIceCandidate', event.candidate)
    }
}


// Listen for remote ICE candidates and add them to the local RTCPeerConnection

socket.on('newIceCandidate', async candidate => {
    try {
        await peerConnection.addIceCandidate(candidate)
    } catch (e) {
        console.log(e)
    }
})

// Is never called
peerConnection.addEventListener('connectionstatechange', event => {
    if (peerConnection.connectionState === 'connected') {
        console.log('CONNECTED PEER')
    }
})


// user 1 receiving data from other
socket.on('answer', async remoteDescription => {
    const remoteDesc = new RTCSessionDescription(remoteDescription)
    await peerConnection.setRemoteDescription(remoteDesc)
})

// user 2 getting init message
socket.on('offer', async offer => {
    peerConnection.setRemoteDescription(new RTCSessionDescription(offer))
    const answer = await peerConnection.createAnswer()
    await peerConnection.setLocalDescription(answer)
    socket.emit('answer', answer)
})

/////////////// Less relevant /////////////////


peerConnection.oniceconnectionstatechange = state => {
    console.log('ice state change!')
}

peerConnection.ontrack = ({
    streams: [stream]
}) => remoteVideo.srcObject = stream


function stop() {

}

start()

控制台输出 对等连接内容

4

1 回答 1

2

在 webrtc 协商之前,您必须将您的轨道添加到 peerconnection 对象。

但是在您的代码中,您没有。

getUserMedia 函数是 Promise。

所以试试这样

// init video media
function start() {
    navigator.mediaDevices.getUserMedia({
        audio: true,
        video: true
    }).then(stream => {
        localVideo.srcObject = stream
        localStream = stream

        for (let track of localStream.getTracks()) {
            peerConnection.addTrack(track, localStream)
        }
    })
}
于 2020-05-11T06:07:00.170 回答