Flutter _网页:无法重新加入我先前离开的频道

yv5phkfx  于 2022-11-30  发布在  Flutter
关注(0)|答案(1)|浏览(96)

我正在开发一个流应用程序:一个应用程序(服务器)广播一个视频,另一个应用程序(客户端)显示这个视频。我使用flutter_webrtc包进行实时通信。我遵循了以下教程:
https://www.youtube.com/watch?v=hAKQzNQmNe0
https://github.com/md-weber/webrtc_tutorial/
目前,服务器端应用程序可以成功创建频道并播放视频,客户端应用程序可以加入该频道并观看视频,但当客户端离开该频道,稍后尝试连接到同一频道时,无法获得视频,只显示黑屏,没有显示错误。
我使用flutter_riverpod作为状态管理,下面的所有代码都在StateNotifiers中。
函数从服务器应用程序端创建通道。
第一个
函数从客户端应用程序端加入通道。
第一次

hpxqektj

hpxqektj1#

经过一番研究,我发现我的问题与Failed to set remote answer sdp: Called in wrong state: stable问题中的问题相同。这是由于一个RTCPeerConnection只能建立一个对等连接这一事实造成的。因此,我可以通过在每次新客户端希望加入通道时在服务器端创建一个新的RTCPeerConnection来解决此问题。

Future<String> _createRoom() async {
    final db = FirebaseFirestore.instance;
    final roomRef = db.collection('rooms').doc();
    await newPeerConnection(roomRef);

    roomId = roomRef.id;

    // Listening for remote session description below
    roomRef.snapshots().listen((snapshot) async {
      final data = snapshot.data();

      if (data != null && data['answer'] != null) {
        final answer = data['answer'] as Map<String, dynamic>;
        final description = RTCSessionDescription(
          answer['sdp'] as String?,
          answer['type'] as String?,
        );

        await peerConnectionList.last.setRemoteDescription(description);
        await newPeerConnection(roomRef);
      }
    });

    // Listen for remote Ice candidates below
    roomRef.collection('calleeCandidates').snapshots().listen((snapshot) {
      for (final change in snapshot.docChanges) {
        if (change.type == DocumentChangeType.added) {
          final data = change.doc.data();

          peerConnectionList.last.addCandidate(
            RTCIceCandidate(
              data?['candidate'] as String?,
              data?['sdpMid'] as String?,
              data?['sdpMLineIndex'] as int?,
            ),
          );
        }
      }
    });

    return roomId!;
}
Future<void> newPeerConnection(DocumentReference roomRef) async {
    final peerConnection = await createPeerConnection(
      configuration,
      offerSdpConstraints,
    );

    _registerPeerConnectionListeners(peerConnection);

    localStream?.getTracks().forEach((track) {
      peerConnection.addTrack(track, localStream!);
    });

    final offer = await peerConnection.createOffer();
    await peerConnection.setLocalDescription(offer);

    final roomWithOffer = <String, dynamic>{'offer': offer.toMap()};
    await roomRef.set(roomWithOffer);

    peerConnectionList.add(peerConnection);
  }

相关问题