100ms Flutter SDK?

100ms

在这里,您将找到使用 100ms iOS/Android SDK 构建视频体验所需的一切。深入了解我们的 SDK、快速入门,将实时视频、语音和屏幕共享添加到您的 Web 和移动应用程序。

? 在此下载示例 iOS 应用: https://testflight.apple.com/join/Uhzebmut

? 在此下载示例 Android 应用: https://appdistribution.firebase.dev/i/b623e5310929ab70

?‍♀️ 如何运行示例应用

  1. 在项目根目录,运行 flutter pub get
  2. 更改目录到 example 文件夹,运行 flutter packages pub run build_runner build --delete-conflicting-outputs
  3. 运行 flutter build iosflutter build apk
  4. 最后,运行 flutter run

? 关键概念

  • Room - Room 代表实时音频、视频会话,是 100mslive 视频 SDK 的基本构建块。
  • Track - Track 代表构成流的音频或视频。
  • Peer - Peer 代表连接到 Room 的所有参与者。Peer 可以是“本地”或“远程”。
  • Broadcast - 本地 Peer 可以将任何消息/数据发送到 Room 中的所有远程 Peer。

生成认证令牌

认证令牌用于 HMSConfig 实例来设置配置。
所以您需要发出一个 HTTP 请求。您可以使用任何包,我们这里使用的是 http 包。
您可以在您的 100ms 控制面板找到您的令牌端点,并在该端点后追加 api/token,然后发出一个 HTTP POST 请求。

示例

http.Response response = await http.post(Uri.parse(Constant.getTokenURL),
        body: {'room_id': room, 'user_id': user, 'role': Constant.defaultRole});

生成令牌后,使用 json 解析它。

var body = json.decode(response.body);
String token = body['token'];

稍后您将需要此令牌,如下所述。

♻️ 设置事件监听器

100ms SDK 提供回调给客户端应用程序,关于用户加入后在 Room 中发生的任何更改或更新,通过实现 HMSUpdateListener。这些更新可用于在屏幕上渲染视频或显示有关 Room 的其他信息。

abstract class HMSUpdateListener {
  /// This will be called on a successful JOIN of the room by the user
  ///
  /// This is the point where applications can stop showing its loading state
  /// - Parameter room: the room which was joined
  void onJoin({required HMSRoom room});

  /// This is called when there is a change in any property of the Room
  ///
  /// - Parameters:
  ///   - room: the room which was joined
  ///   - update: the triggered update type. Should be used to perform different UI Actions
  void onRoomUpdate({required HMSRoom room, required HMSRoomUpdate update});

  /// This will be called whenever there is an update on an existing peer
  /// or a new peer got added/existing peer is removed.
  ///
  /// This callback can be used to keep a track of all the peers in the room
  /// - Parameters:
  ///   - peer: the peer who joined/left or was updated
  ///   - update: the triggered update type. Should be used to perform different UI Actions
  void onPeerUpdate({required HMSPeer peer, required HMSPeerUpdate update});

  /// This is called when there are updates on an existing track
  /// or a new track got added/existing track is removed
  ///
  /// This callback can be used to render the video on screen whenever a track gets added
  /// - Parameters:
  ///   - track: the track which was added, removed or updated
  ///   - trackUpdate: the triggered update type
  ///   - peer: the peer for which track was added, removed or updated
  void onTrackUpdate(
      {required HMSTrack track,
      required HMSTrackUpdate trackUpdate,
      required HMSPeer peer});

  /// This will be called when there is an error in the system
  ///
  /// and SDK has already retried to fix the error
  /// - Parameter error: the error that occurred
  void onError({required HMSError error});

  /// This is called when there is a new broadcast message from any other peer in the room
  ///
  /// This can be used to implement chat is the room
  /// - Parameter message: the received broadcast message
  void onMessage({required HMSMessage message});

  /// This is called when someone asks for change or role
  ///
  /// for eg. admin can ask a peer to become host from guest.
  /// this triggers this call on peer's app
  void onRoleChangeRequest({required HMSRoleChangeRequest roleChangeRequest});

  /// This is called every 1 second with list of active speakers
  ///
  ///    A HMSSpeaker object contains -
  ///    - peerId: the peer identifier of HMSPeer who is speaking
  ///    - trackId: the track identifier of HMSTrack which is emitting audio
  ///    - audioLevel: a number within range 1-100 indicating the audio volume
  ///
  /// A peer who is not present in the list indicates that the peer is not speaking
  ///
  /// This can be used to highlight currently speaking peers in the room
  /// - Parameter speakers: the list of speakers
  void onUpdateSpeakers({required List<HMSSpeaker> updateSpeakers});

  void onReconnecting();

  void onReconnected();
}

? 如何监听 Track、Peer 和 Room 的更新?

HMS SDK 通过 HMSUpdateListener 中的回调向应用程序发送关于 HMSPeer、HMSTrack 或 HMSRoom 任何更改的更新。
应用程序需要在 onPeerUpdate、onTrackUpdate 或 onRoomUpdate 中监听相应的更新。

以下是 SDK 发出的不同类型的更新:

  HMSPeerUpdate
    case PEER_JOINED A new peer joins the room
    case PEER_LEFT - An existing peer leaves the room
    case BECAME_DOMINANT_SPEAKER - A peer becomes a dominant speaker
    case NO_DOMINANT_SPEAKER - There is silence in the room (No speaker is detected)
    
  HMSTrackUpdate
    case TRACK_ADDED - A new track is added by a remote peer
    case TRACK_REMOVED - An existing track is removed from a remote peer
    case TRACK_MUTED - An existing track of a remote peer is muted
    case TRACK_UNMUTED - An existing track of a remote peer is unmuted
    case TRACK_DESCRIPTION_CHANGED - The optional description of a track of a remote peer is changed

? 如何知道 Track 的类型和来源?

HMSTrack 包含一个名为 source 的字段,它表示 Track 的来源。
Source 可以具有以下值:regular(正常)、screen(用于屏幕共享)和 plugin(用于插件)。

要了解 Track 的类型,请检查 type 的值,它将是以下枚举值之一:AUDIO 或 VIDEO。

? 提供加入配置

要加入一个 Room(按照上一节所述步骤创建),客户端需要创建一个 HMSConfig 实例,并使用该实例调用 HMSSDK 实例的 join 方法。

// Create a new HMSConfig
HMSConfig config = HMSConfig( userId: userId,
                              roomId: roomId,
                              authToken: token,
                              userName: userName);

userId:应是唯一的,我们使用 Uuid 包来生成一个。
roomId:您想加入的 Room 的 ID。
token:遵循上述步骤 1 来生成令牌。
userName:您想用于加入 Room 的名称。

? 加入 Room

使用 HMSConfig 和 HMSUpdateListener 实例来调用上面创建的 HMSSDK 实例上的 join 方法。
一旦 Join 成功,所有回调都会在 Room 的每次更改时继续接收,应用程序可以据此做出反应。

HMSMeeting meeting = HMSMeeting()
meeting.joinMeeting(config: this.config);

? 离开 Room

在 HMSSDK 实例上调用 leave 方法。

meeting.leave() // to leave a room

? 静音/取消静音本地音频

// Turn on
meeting.switchAudio(isOn:true)
// Turn off  
meeting.switchAudio(isOn:false)

? 静音/取消静音本地视频

meeting.startCapturing()

meeting.stopCapturing()

meeting.switchCamera()

? HMSTracks 详解

HMSTrackHMSSDK 中使用的所有 Track 的超类。它的层次结构如下:

HMSTrack
    - AudioTrack
        - LocalAudioTrack
        - RemoteAudioTrack
    - VideoTrack
        - LocalVideoTrack
        - RemoteVideoTrack

? 显示 Track

要显示视频 Track,首先获取 HMSVideoTrack 并使用 setVideoTrack 函数将其传递给 HMSVideoView。请确保将 HMSVideoView 附加到您的 UI 层次结构。

VideoView(
    track: videoTrack,
    args: {
      'height': customHeight,
      'width': customWidth,
    },
  );

更改角色

要更改角色,您需要提供选定 Peer 的 peerId 和 roles 中的新 roleName。如果 forceChange 为 true,系统将提示用户进行更改。如果 forceChange 为 false,用户将收到一个接受/拒绝角色的提示。
调用 changeRole 后,HMSUpdateListener 的 onRoleChangeRequest 将会在选定用户的端被调用。

 meeting.changeRole(
        peerId: peerId, roleName: roleName, forceChange: forceChange);

? 聊天消息

您可以从本地 Peer 向 Room 中的所有远程 Peer 发送聊天或其他任何类型消息。

要发送消息,首先创建一个 HMSMessage 对象实例。

将要发送的信息添加到 HMSMessagemessage 属性中。

然后,在 HMSMeeting 实例上使用 Future<void> sendMessage(String message) 函数。

当您(本地 Peer)从其他人(任何远程 Peer)收到消息时,HMSUpdateListenervoid onMessage({required HMSMessage message}) 函数将被调用。

// following is an example implementation of chat messaging

// to send a broadcast message
String message = 'Hello World!'
meeting.sendMessage(message);  // meeting is an instance of `HMSMeeting` object



// receiving messages
// the object conforming to `HMSUpdateListener` will be invoked with `on(message: HMSMessage)`, add your logic to update Chat UI within this listener
void onMessage({required HMSMessage message}){
    let messageReceived = message.message // extract message payload from `HMSMessage` object that is received
    // update your Chat UI with the messageReceived
}

?‍♀️ 在 示例应用文件夹 中查看示例实现。

? 预览

您可以使用我们的预览功能在加入 Room 之前静音/取消静音音频/视频。

您可以使用此 abstract class HMSPreviewListener 实现自己的预览监听器。

abstract class HMSPreviewListener {

  //you will get all error updates here
  void onError({required HMSError error});

  //here you will get room instance where you are going to join and your own local tracks to render the video by checking the type of trackKind and then using the 
  //above mentioned VideoView widget
  void onPreview({required HMSRoom room, required List<HMSTrack> localTracks});
}

? 设置指南

  1. https://dashboard.100ms.live/register 注册,然后访问开发者选项卡以访问您的凭据。

  2. 在此处 熟悉令牌和安全

  3. 完成 认证令牌快速入门指南 中的步骤。

  4. 通过 pub.dev 获取 HMSSDK。将 hmssdk_flutter 添加到您的 pubspec.yaml。

Android 集成

在 Android AndroidManifest.xml 文件中添加以下权限。

<uses-feature android:name="android.hardware.camera"/>

<uses-feature android:name="android.hardware.camera.autofocus"/>

<uses-permission android:name="android.permission.CAMERA"/>

<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>

<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>

<uses-permission android:name="android.permission.RECORD_AUDIO"/>

<uses-permission android:name="android.permission.BLUETOOTH"/>

<uses-permission android:name="android.permission.INTERNET"/>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

☝️ 先决条件

  • 支持 Android API 级别 24 及更高版本。
  • 支持 Java 8。

? 支持的设备

Android SDK 支持 Android API 级别 21 及更高版本。它为 armeabi-v7a、arm64-v8a、x86 和 x86_64 架构构建。

iOS 集成

在 iOS Info.plist 文件中添加以下权限。

<key>NSMicrophoneUsageDescription</key>
<string>{YourAppName} wants to use your microphone</string>

<key>NSCameraUsageDescription</key>
<string>{YourAppName} wants to use your camera</string>

<key>NSLocalNetworkUsageDescription</key>
<string>{YourAppName} App wants to use your local network</string>

GitHub

https://github.com/100mslive/100ms-flutter