使用go2Rtc传输webRtc视频流给前端

62 阅读1分钟
import { ref } from 'vue'

export function useRobotGo2WebRTC(rtspUrl) {
  const rtcStatus = ref('未连接')
  const streaming = ref(false)
  const videoStream = ref(null)

  let peerConnection = null

  const connectWebRTC = async (videoRef = null) => {
    try {
      peerConnection = new RTCPeerConnection({
        iceServers: [
          { urls: 'stun:stun.l.google.com:19302' }
        ]
      })

      peerConnection.ontrack = (event) => {
        if (event.streams[0]) {
          videoStream.value = event.streams[0]
          if (videoRef && videoRef.value) {
            videoRef.value.srcObject = event.streams[0]
          }
          streaming.value = true
        }
      }

      peerConnection.onconnectionstatechange = () => {
        const state = peerConnection.connectionState
        rtcStatus.value = state
      }

      await setupWebRTCWithGo2RTC()

    } catch (error) {
      console.log('WebRTC连接失败: ' + error.message)
    }
  }

  const setupWebRTCWithGo2RTC = async () => {
    try {
      const offer = await peerConnection.createOffer({
        offerToReceiveVideo: true,
        offerToReceiveAudio: true
      })
      await peerConnection.setLocalDescription(offer)
      console.log('active-env',import.meta.env.MODE)
      const baseUrl = import.meta.env.MODE === 'development' ? '/go2rtc' : import.meta.env.VITE_APP_BASE_GO2RTC_URL
      const apiUrl = `${baseUrl}/api/webrtc?src=${rtspUrl}`
      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/sdp'
        },
        body: offer.sdp
      })
      if (!response.ok) {
        const errorText = await response.text()
        console.log(`go2rtc WebRTC API错误: ${response.status} - ${errorText}`)
      }
      const answerSdp = await response.text()
      const answer = new RTCSessionDescription({
        type: 'answer',
        sdp: answerSdp
      })
      await peerConnection.setRemoteDescription(answer)
    } catch (error) {
      console.log('go2rtc WebRTC握手失败: ' + error.message)
    }
  }

  const disconnect = () => {
    if (peerConnection) {
      peerConnection.close()
      peerConnection = null
    }
    videoStream.value = null
    streaming.value = false
    rtcStatus.value = '未连接'
  }

  return {
    rtcStatus,
    streaming,
    videoStream,
    connectWebRTC,
    disconnect
  }
}