基于peerjs的webrtc通话测试

59

在线体验demo

1.发起

//1.获取音频or视频
const stream = await navigator.mediaDevices.getUserMedia({
  audio: true,
  video: false
})

// 2. 使用对方ID发起呼叫
const call = peer.call(remotePeerId, stream)
// 3. 处理通话连接
call.on('stream', (remoteStream) => {
  // 播放对方的音频流
  const audio = new Audio()
  audio.srcObject = remoteStream
  audio.play()
})

2.接听

// 监听来电
peer.on('call', async (call) => {
  // 1. 获取本地音频流
  const stream = await navigator.mediaDevices.getUserMedia({
    audio: true
  })
  
  // 2. 应答通话并发送本地流
  call.answer(stream)
  
  // 3. 处理对方的音频流
  call.on('stream', (remoteStream) => {
    // 播放对方的音频
    const audio = new Audio()
    audio.srcObject = remoteStream
    audio.play()
  })
})