peerConnection.ontrack 无法正常工作我该如何解决这个问题?请帮助我

问题描述 投票:0回答:1

这是我的 App.tsx 文件。我正在从 Web 应用程序接收流内容,并将 WebRTC 与 React Native 结合使用。虽然一切似乎都工作正常,但我面临着peerConnection.ontrack 未触发的问题。没有显示任何控制台日志,并且我没有收到任何流数据来显示流。谁能帮我解决这个问题?我也有一些相关的问题,但这些问题与 Web 应用程序有关,而不是 React Native。

// App.tsx
import React, {useState} from 'react';
import {View, Text, StyleSheet} from 'react-native';

import {firebaseConfig} from './firebaseConfig';
import OfferCodeScreen from './OfferCodeScreen';

import app from '@react-native-firebase/app';
import database from '@react-native-firebase/database';
import {
  RTCPeerConnection,
  RTCIceCandidate,
  RTCSessionDescription,
  RTCView,
  MediaStream,
} from 'react-native-webrtc';
import RTCTrackEvent from 'react-native-webrtc/lib/typescript/RTCTrackEvent';

// Initialize Firebase if not already
if (app.apps.length === 0) {
  app.initializeApp(firebaseConfig);
}

// STUN / TURN config
const rtcConfig: RTCConfiguration = {
  iceServers: [{urls: 'stun:stun.l.google.com:19302'}],
};

const App = () => {
  const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null);
  const [connected, setConnected] = useState(false);

  const connectWithOfferCode = async (offerCode: string) => {
    try {
      // 1. Get the offer from Firebase
      const offerSnapshot = await database()
        .ref(`offers/${offerCode}`)
        .once('value');
      const offerData = offerSnapshot.val();

      if (!offerData) {
        console.error('No offer found for this code.');
        return;
      }

      // 2. Create a new PeerConnection
      const peerConnection = new RTCPeerConnection(rtcConfig);

      // 3. Set remote description with the web's offer
      await peerConnection.setRemoteDescription(
        new RTCSessionDescription(offerData),
      );

      // 4. Create answer and set local description
      const answer = await peerConnection.createAnswer();
      await peerConnection.setLocalDescription(answer);

      // 5. Post the answer to Firebase
      await database().ref(`answers/${offerCode}`).set({
        type: answer.type,
        sdp: answer.sdp,
      });

      // 6. Listen for the web’s ICE candidates
      database()
        .ref(`candidates/${offerCode}/webToMobile`)
        .on('child_added', async snapshot => {
          const candidateData = snapshot.val();
          if (candidateData) {
            const candidate = new RTCIceCandidate(candidateData);
            await peerConnection.addIceCandidate(candidate);
          }
        });

      // 7. Send our ICE candidates to the web
      peerConnection.onicecandidate = (event: any) => {
        if (event.candidate) {
          console.log('onicecandidate', event.candidate);
          database()
            .ref(`candidates/${offerCode}/mobileToWeb`)
            .push(event.candidate.toJSON());
        }
      };

      // 8. On track, set the remote stream
      peerConnection.ontrack = (event: any) => {
        console.log('coming here');
        const [stream] = event.streams;
        console.log('Stream Data: ', stream);
        setRemoteStream(stream);
        setConnected(true);
        console.log('connected: ', connected);
      };

      console.log('Connected with offer code:', offerCode);
    } catch (err) {
      console.error('Error connecting:', err);
    }
  };

  return (
    <View style={styles.container}>
      {!connected ? (
        <>
          <Text style={styles.title}>Enter Offer Code to Connect</Text>
          <OfferCodeScreen onConnect={connectWithOfferCode} />
        </>
      ) : (
        <>
          <Text style={styles.title}>
            Connected! Displaying Screen Share...
          </Text>
          {remoteStream && (
            <RTCView streamURL={remoteStream.toURL()} style={styles.video} />
          )}
        </>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {flex: 1, backgroundColor: '#fff', paddingTop: 40},
  title: {fontSize: 18, textAlign: 'center', marginBottom: 20},
  video: {flex: 1, backgroundColor: 'black'},
});

export default App;


 
reactjs react-native webrtc react-native-webrtc
1个回答
0
投票

我尝试解决该问题但找不到解决方案,因此我决定使用新的 Expo DOM 组件。这些组件允许我直接在 React Native 文件中编写 React.js 代码。然后,“use dom”指令将文件转换为本机 WebView 代理组件。

想要更深入的了解和详细指导,可以参考Expo官方博文和文档:

https://expo.dev/blog/the-magic-of-expo-dom-components https://docs.expo.dev/guides/dom-components/

© www.soinside.com 2019 - 2024. All rights reserved.