Flutter API 说明
Flutter plugin tirtc_flutter 提供客户端 Dart API,适用于用 Flutter 开发 Android、iOS、macOS、OpenHarmony / HarmonyOS NEXT 客户端。
如果你还没有完成包接入、原生工程配置或连接流程准备,先看 Flutter SDK 接入。
适用范围
TiRTC Flutter SDK 面向 Android、iOS、macOS、OpenHarmony / HarmonyOS NEXT 客户端应用。你的项目需要使用 Flutter >=3.13.0,Dart >=3.1.0 <4.0.0。
最低运行系统版本和平台要求:
- Android 5.0(API Level 21)及以上
- iOS
13.0及以上 - macOS
11.5及以上 - OpenHarmony / HarmonyOS NEXT,OpenHarmony SDK
12及以上
在 Dart 代码中导入 API
在 Dart 文件中,从 tirtc_flutter 按需导入业务代码使用的对象。示例代码使用统一导出入口。
import 'package:tirtc_flutter/tirtc_flutter.dart';生命周期与调用顺序
典型客户端流程是:连接一个设备端,播放设备端音视频,并按需收发命令或发起语音对讲。主干从 TiRtc.initialize(...) 开始,以 disconnect() 和 dispose() 收尾。
初始化:传入
AppId,启动 SDK 运行时。dartawait TiRtc.initialize(TiRtcInitOptions(appId: appId));创建连接:创建
TiRtcConn,并在连接前设置状态、命令和流消息回调。dartfinal TiRtcConn conn = TiRtcConn() ..onStateChanged = handleConnStateChanged ..onCommand = handleCommand ..onStreamMessage = handleStreamMessage;准备播放:在发起连接前创建音频输出和视频输出,并指定要播放的
streamId。dartfinal TiRtcAudioOutput audioOutput = TiRtcAudioOutput(); audioOutput.attach(connection: conn, streamId: audioStreamId); final TiRtcVideoOutput videoOutput = TiRtcVideoOutput(); videoOutput.attach(connection: conn, streamId: videoStreamId);渲染视频:在界面中挂载
videoOutput.view(),让视频输出有对应的显示位置。dartWidget build(BuildContext context) => videoOutput.view();发起连接:传入目标设备的
device_id和业务服务端签发的token。dartconn.connect(remoteId: remoteId, token: token);请求媒体:连接进入
connected后,按需请求设备端发送音频流和视频流。dartconn.subscribeAudio(streamId: audioStreamId); // 连接成功后订阅音频 conn.subscribeVideo(streamId: videoStreamId); // 连接成功后订阅视频命令交互:连接进入
connected后,按需通过命令通道和设备端交换业务数据。dartconn.sendCommand(commandId: commandId, data: data); // 需要命令交互时调用 // 收到设备端命令时,在 handleCommand(commandId, data) 中处理。语音对讲(按需):应用获得系统麦克风权限后,创建音频输入,绑定到同一条连接,并启动采集发送。
dartfinal TiRtcAudioInput talkbackInput = TiRtcAudioInput(); await talkbackInput.setOptions(talkbackOptions); await talkbackInput.attach(connection: conn, streamId: talkbackStreamId); await talkbackInput.start();收尾释放:业务结束时先释放按需创建的输入对象,再按订阅、输出、连接的顺序收尾。
dartawait talkbackInput.stop(); // 创建了 talkbackInput 时调用 await talkbackInput.detach(connection: conn); await talkbackInput.dispose(); conn.unsubscribeAudio(streamId: audioStreamId); // 停止播放时取消音频订阅 conn.unsubscribeVideo(streamId: videoStreamId); // 停止播放时取消视频订阅 audioOutput.detach(); videoOutput.detach(); audioOutput.dispose(); videoOutput.dispose(); conn.disconnect(); conn.dispose();
TiRtcInitOptions
TiRtcInitOptions 是 TiRtc.initialize(...) 的参数对象。
初始化时必须传 appId,取值为你的 AppId。
const TiRtcInitOptions({
appId: '', // 必填:你的 AppId
endpoint: '', // 切换自部署云端实例或测试、联调环境时设置,例如 "https://ep-tirtc.my-domain.com";其他情况保持空字符串
consoleLogEnabled: false, // true 时同时把 SDK 日志打印到控制台
})TiRtc
TiRtc 提供初始化和错误码名称转换入口。
// 初始化 SDK。返回 0 表示成功,非 0 为错误码。
// 重复调用成功时返回 0,不会替换已生效的配置。
static Future<int> initialize(TiRtcInitOptions config)
// 把错误码转成错误名称。
static String errorToString(int code)示例:
final int code = await TiRtc.initialize(
const TiRtcInitOptions(appId: 'your-app-id'),
);
if (code != 0) {
debugPrint('initialize failed: ${TiRtc.errorToString(code)} ($code)');
}TiRtcConn
TiRtcConn 表示客户端到远端设备的一条连接。创建对象不会立即发起连接;通常先设置回调,再调用 connect(...)。连接建立后,可以通过它发送命令、发送流消息、发起媒体订阅和请求视频关键帧。
音频播放和视频显示由 TiRtcAudioOutput / TiRtcVideoOutput 负责,TiRtcConn 本身不播放也不显示媒体。
状态
TiRtcConnState.idle:连接对象已创建,但还没有开始连接。TiRtcConnState.connecting:连接请求已提交,正在等待结果。TiRtcConnState.connected:连接已经建立,可收发命令、流消息,发起媒体订阅和关键帧请求。TiRtcConnState.disconnected:连接失败、对端断开或调用disconnect()后进入该状态。
属性和回调
// 当前连接状态。
TiRtcConnState get state
// 连接状态变化时触发。errorCode 为 0 表示本次状态变化没有错误;非 0 为错误码。
TiRtcOnConnStateChanged? onStateChanged
// 收到设备端命令时触发。
TiRtcOnConnCommand? onCommand
// 收到设备端的流消息时触发。
TiRtcOnConnStreamMessage? onStreamMessage相关类型:
typedef TiRtcOnConnStateChanged = void Function(
TiRtcConnState state,
int errorCode,
);
typedef TiRtcOnConnCommand = void Function(
int commandId,
Uint8List data,
);
typedef TiRtcOnConnStreamMessage = void Function(
int streamId,
int timestampMs,
Uint8List data,
);方法
// 创建连接对象;构造函数本身不会发起连接。通常先设置回调,再调用 connect。
TiRtcConn()
// 发起连接;初始化完成并拿到连接凭证后调用。
// remoteId 是连接目标;连接设备端时传目标设备的 device_id,例如 "PRODFENGXXXX"。
// token 是业务服务端为本次连接签发的 token,二者不能为空。
// 返回 0 只表示请求已提交,最终连接结果看 onStateChanged;非 0 为错误码。
int connect({required String remoteId, required String token})
// 断开当前连接;业务结束、切换设备或重新连接前调用。对象仍可重新 connect。
int disconnect()
// 释放连接对象;确认不再使用这条连接后调用。调用后不要再使用这个实例。
void dispose()
// 在命令通道上发送自定义命令;连接进入 connected 后调用。
int sendCommand({required int commandId, required Uint8List data})
// 发送流消息;连接进入 connected 后调用。
// streamId 按 stream_id 约定使用 0..15,两端需要提前约定消息语义。
int sendStreamMessage({
required int streamId,
required int timestampMs,
required Uint8List data,
})
// 请求远端开始发送指定 streamId 的音频流;连接进入 connected 后调用。
// streamId 按 stream_id 约定使用 0..15。
// 这个方法只请求远端发送音频,不会自动播放。
// 播放远端音频前,先调用 TiRtcAudioOutput.attach(...) 指定要播放的 connection 和 streamId;然后调用 connect(...) 建立连接。
// 连接成功后,再调用 subscribeAudio(...) 请求远端发送这路音频。
int subscribeAudio({required int streamId})
// 请求远端停止发送指定 streamId 的音频流;streamId 按 stream_id 约定使用 0..15。
// 不会停止已经创建的 TiRtcAudioOutput。停止播放时再调用 TiRtcAudioOutput.detach()。
int unsubscribeAudio({required int streamId})
// 请求远端开始发送指定 streamId 的视频流;连接进入 connected 后调用。
// streamId 按 stream_id 约定使用 0..15。
// 这个方法只请求远端发送视频,不会自动显示。
// 显示远端视频前,先调用 TiRtcVideoOutput.attach(...) 指定要显示的 connection 和 streamId;然后调用 connect(...) 建立连接。
// 连接成功后,再调用 subscribeVideo(...) 请求远端发送这路视频。
int subscribeVideo({required int streamId})
// 请求远端停止发送指定 streamId 的视频流;streamId 按 stream_id 约定使用 0..15。
// 不会停止已经创建的 TiRtcVideoOutput。停止显示时再调用 TiRtcVideoOutput.detach()。
int unsubscribeVideo({required int streamId})
// 向远端请求指定视频流的关键帧;连接已建立且远端正在发送该视频流时调用。
// streamId 按 stream_id 约定使用 0..15。
int requestKeyFrame({required int streamId})示例:
final TiRtcConn conn = TiRtcConn()
..onStateChanged = (TiRtcConnState state, int errorCode) {
if (errorCode == 0) {
debugPrint('conn state=$state');
return;
}
debugPrint('conn state=$state error=${TiRtc.errorToString(errorCode)} ($errorCode)');
}
..onCommand = (int commandId, Uint8List data) {
debugPrint('command=$commandId bytes=${data.length}');
};
final int code = conn.connect(remoteId: remoteId, token: token);
if (code != 0) {
debugPrint('connect failed: ${TiRtc.errorToString(code)} ($code)');
}
// 结束时:
conn.disconnect();
conn.dispose();TiRtcAudioOutputOptions
TiRtcAudioOutputOptions 配置 TiRtcAudioOutput 的音频输出参数。只需要填写要覆盖默认值的字段。
const TiRtcAudioOutputOptions({
agcLevel: TiRtcAudioAgcLevel.disabled, // 自动增益等级
ansLevel: TiRtcAudioAnsLevel.disabled, // 自动噪声抑制等级
bufferStrategy: TiRtcOutputBufferStrategy.automatic, // 输出缓冲策略
// 最大输出缓冲水位,单位为毫秒;仅 automatic 有效。
// null 表示由 SDK 自动决定。
maxBufferWatermarkMs: null,
})相关枚举:
// 自动增益控制等级。
enum TiRtcAudioAgcLevel {
disabled, // 关闭
low, // 低
medium, // 中
high, // 高
}
// 自动噪声抑制等级。
enum TiRtcAudioAnsLevel {
disabled, // 关闭
low, // 低
medium, // 中
high, // 高
}
// 输出缓冲策略。
enum TiRtcOutputBufferStrategy {
automatic, // SDK 根据当前平台和链路状态决定缓冲策略
noBuffer, // 不使用输出缓冲;不要同时设置 maxBufferWatermarkMs
}TiRtcAudioOutput
TiRtcAudioOutput 用来播放某条远端音频流。 播放远端音频前,先创建 TiRtcAudioOutput,调用 attach(...) 指定要播放的 connection 和 streamId,再调用 connect(...) 建立连接;连接成功后,调用 TiRtcConn.subscribeAudio(...) 请求远端发送这路音频。 attach(...) 成功只表示播放对象已经知道要播放哪路音频。如果远端还没有发送这路音频,用户仍然听不到声音。 attach(...) 只选择这路音频由哪个 TiRtcAudioOutput 播放;subscribeAudio(...) 才会请求远端发送。
状态
TiRtcAudioOutputState.idle:还没有选择要播放的远端音频流,或已经detach()。TiRtcAudioOutputState.buffering:已经选择要播放的远端音频流,正在等待可播放数据。TiRtcAudioOutputState.playing:正在播放远端音频。TiRtcAudioOutputState.failed:播放路径发生错误。
属性和回调
// 当前音频播放状态。
TiRtcAudioOutputState get state
// 播放状态变化时触发。
TiRtcOnAudioOutputStateChanged? onStateChanged
// 音频输出对象发生错误时触发。
TiRtcOnAudioOutputError? onError相关类型:
typedef TiRtcOnAudioOutputStateChanged = void Function(
TiRtcAudioOutputState state,
);
typedef TiRtcOnAudioOutputError = void Function(int code);方法
// 创建音频输出对象。
TiRtcAudioOutput()
// 配置音频输出参数;创建对象后、attach 前调用。
// 返回 0 表示成功,非 0 为错误码;已绑定后调用会返回错误码。
int configure(TiRtcAudioOutputOptions options)
// 指定这个输出对象要播放的远端音频流。通常在 connect 前调用;如果输出对象晚创建,也可以在连接建立后调用。
// 远端发送这路音频后,用户才会听到声音。
int attach({required TiRtcConn connection, required int streamId})
// 停止使用这个输出对象播放当前音频流;切换流或释放对象前调用。成功后状态回到 idle。
int detach()
// 释放音频输出对象;通常在 detach 后调用。调用后不要再使用这个实例。
void dispose()示例:
final TiRtcAudioOutput audioOutput = TiRtcAudioOutput()
..onError = (int code) {
debugPrint('audio output error: ${TiRtc.errorToString(code)} ($code)');
};
final int code = audioOutput.attach(connection: conn, streamId: 10);
if (code != 0) {
debugPrint('audio attach failed: ${TiRtc.errorToString(code)} ($code)');
}
// 结束时:
audioOutput.detach();
audioOutput.dispose();TiRtcVideoOutputOptions
TiRtcVideoOutputOptions 配置 TiRtcVideoOutput 的解码和缓冲参数。只需要填写要覆盖默认值的字段。
const TiRtcVideoOutputOptions({
// 解码偏好:0 自动,1 软件解码,2 硬件解码。
// 这只是请求偏好,实际选择取决于设备、系统和视频编码格式。
decoderPreference: 0,
bufferStrategy: TiRtcOutputBufferStrategy.automatic, // 输出缓冲策略
// 最大输出缓冲水位,单位为毫秒;仅 automatic 有效。
// null 表示由 SDK 自动决定。
maxBufferWatermarkMs: null,
})相关枚举:
// 输出缓冲策略。
enum TiRtcOutputBufferStrategy {
automatic, // SDK 根据当前平台和链路状态决定缓冲策略
noBuffer, // 不使用输出缓冲;不要同时设置 maxBufferWatermarkMs
}TiRtcVideoOutput
TiRtcVideoOutput 用来显示某条远端视频流。 显示远端视频前,先创建 TiRtcVideoOutput,调用 attach(...) 指定要显示的 connection 和 streamId,再调用 connect(...) 建立连接;连接成功后,调用 TiRtcConn.subscribeVideo(...) 请求远端发送这路视频。 attach(...) 成功只表示输出对象已经准备好。如果远端还没有发送这路视频,页面不会出画面。 attach(...) 只选择这路视频由哪个 TiRtcVideoOutput 显示;subscribeVideo(...) 才会请求远端发送。
状态
TiRtcVideoOutputState.idle:还没有选择要显示的远端视频流,或已经detach()。TiRtcVideoOutputState.buffering:已经选择要显示的远端视频流,正在等待可渲染数据或渲染视图准备。TiRtcVideoOutputState.rendering:正在渲染远端视频。TiRtcVideoOutputState.failed:视频输出路径发生错误。
属性和回调
// 最近一次远端画面渲染尺寸。还没有画面或已经 detach 时可能为 null。
Size? get renderSize
// 播放状态变化时触发。
TiRtcOnVideoOutputStateChanged? onStateChanged
// 远端画面尺寸变化时触发。
TiRtcOnVideoOutputRenderSizeChanged? onRenderSizeChanged
// 视频输出对象发生错误时触发。
TiRtcOnVideoOutputError? onError相关类型:
typedef TiRtcOnVideoOutputStateChanged = void Function(
TiRtcVideoOutputState state,
);
typedef TiRtcOnVideoOutputRenderSizeChanged = void Function(Size size);
typedef TiRtcOnVideoOutputError = void Function(int code);方法
// 创建视频输出对象。
TiRtcVideoOutput()
// 设置视频输出参数;创建对象后、attach 前调用。
// 返回 0 表示成功,非 0 为错误码;需要修改参数时先 detach,再重新 setOptions 和 attach。
int setOptions(TiRtcVideoOutputOptions options)
// 指定这个输出对象要显示的远端视频流。通常在 connect 前调用;如果输出对象晚创建,也可以在连接建立后调用。
// 远端发送这路视频后,页面才会出画面。
int attach({required TiRtcConn connection, required int streamId})
// 停止使用这个输出对象显示当前视频流;切换流或释放对象前调用。成功后状态回到 idle,并清空 renderSize。
int detach()
// 返回这个输出对象对应的 Flutter 渲染视图;需要显示远端视频时在 build 中使用。
// 同一个输出对象同时只支持挂载一个 view。
Widget view()
// 释放视频输出对象和相关系统资源;通常在 detach 后调用。调用后不要再使用这个实例。
void dispose()示例:
final TiRtcVideoOutput videoOutput = TiRtcVideoOutput()
..onRenderSizeChanged = (Size size) {
debugPrint('remote video size=${size.width}x${size.height}');
};
final int code = videoOutput.attach(connection: conn, streamId: 11);
if (code != 0) {
debugPrint('video attach failed: ${TiRtc.errorToString(code)} ($code)');
}
// Widget tree 中挂载:
Widget build(BuildContext context) => videoOutput.view();TiRtcAudioInputOptions
TiRtcAudioInputOptions 配置 TiRtcAudioInput 的麦克风采集和本地音频发送参数。配置会在下一次采集启动时生效;运行中调用 setOptions(...) 会返回错误码。
const TiRtcAudioInputOptions({
codec: TiRtcAudioCodec.g711a, // 本地音频传输编码
sampleRate: TiRtcAudioSampleRate.rate16k, // 麦克风采样率
channels: TiRtcAudioChannelCount.mono, // 声道数;公开能力只支持单声道
aecMode: TiRtcAudioAecMode.disabled, // 回声消除模式
agcLevel: TiRtcAudioAgcLevel.disabled, // 自动增益等级
ansLevel: TiRtcAudioAnsLevel.disabled, // 自动噪声抑制等级
})相关枚举:
// 本地音频传输编码。
enum TiRtcAudioCodec {
g711a,
aac,
pcm,
}
// 麦克风采样率。
enum TiRtcAudioSampleRate {
rate8k,
rate16k,
}
// 声道数。公开能力只支持单声道。
enum TiRtcAudioChannelCount {
mono,
}
// 回声消除模式。
enum TiRtcAudioAecMode {
disabled, // 关闭
enabled, // 开启
}
// 自动增益控制等级。
enum TiRtcAudioAgcLevel {
disabled, // 关闭
low, // 低
medium, // 中
high, // 高
}
// 自动噪声抑制等级。
enum TiRtcAudioAnsLevel {
disabled, // 关闭
low, // 低
medium, // 中
high, // 高
}TiRtcAudioInput
TiRtcAudioInput 采集本地麦克风声音,并通过已建立的连接发送给远端设备。常见用途是语音对讲或语音回复。
应用需要自己申请麦克风权限;SDK 不会替应用弹出系统权限申请框。
状态
TiRtcInputState.idle:输入对象已创建,但还没有开始采集。TiRtcInputState.running:正在采集并传输本地音频。TiRtcInputState.stopped:已停止采集;当前绑定仍可保留给后续start()复用。TiRtcInputState.failed:采集或传输路径发生错误。
属性和回调
// 当前本地音频输入状态。
TiRtcInputState get state
// 输入状态变化时触发。
TiRtcOnInputStateChanged? onStateChanged
// 本地音频输入发生错误时触发。message 可能为空。
TiRtcOnInputError? onError相关类型:
typedef TiRtcOnInputStateChanged = void Function(
TiRtcInputState state,
);
typedef TiRtcOnInputError = void Function(
int code,
String? message,
);方法
// 创建本地音频输入对象。
TiRtcAudioInput()
// 设置下次采集使用的参数;创建对象后、start 前调用。
// 返回 0 表示成功,非 0 为错误码;正在采集时调用会返回错误码。
Future<int> setOptions(TiRtcAudioInputOptions options)
// 把本地麦克风音频通过指定连接和 streamId 发送给远端设备。
// 连接必须已进入 connected;在 start 前调用,streamId 使用 0..15。
// 重复相同绑定返回 0;更换连接或 streamId 前先 detach。
Future<int> attach({required TiRtcConn connection, required int streamId})
// 开始麦克风采集和传输;返回 0 表示成功,非 0 为错误码。
// 调用 start 前,应用必须确保已经获得系统麦克风权限;SDK 不负责申请该权限。
// 还没有 attach 时会返回错误码。
Future<int> start()
// 停止采集和传输,但保留当前绑定;已经停止时调用也返回 0。
Future<int> stop()
// 移除当前连接上的本地音频绑定;停止发送、切换连接或切换 streamId 前调用。
// 运行中先 stop 再 detach。
Future<int> detach({required TiRtcConn connection})
// 释放本地音频输入对象并清理绑定;通常在 stop 和 detach 后调用。调用后不要再使用这个实例。
Future<void> dispose()示例:
final TiRtcAudioInput input = TiRtcAudioInput()
..onError = (int code, String? message) {
debugPrint('audio input error: ${TiRtc.errorToString(code)} ($code) ${message ?? ''}');
};
final int attachCode = await input.attach(connection: conn, streamId: 14);
if (attachCode == 0) {
await input.start();
}
// 结束时:
await input.stop();
await input.detach(connection: conn);
await input.dispose();TiRtcLogging
TiRtcLogging 用于上传当前 SDK 日志。排查问题时,把上传成功返回的 logId 提供给支持人员。
// 上传当前 SDK 日志;code == 0 且 logId != null 表示上传成功。
static Future<({int code, String? logId})> upload()示例:
final ({int code, String? logId}) result = await TiRtcLogging.upload();
if (result.code == 0 && result.logId != null) {
debugPrint('TiRTC logId=${result.logId}');
}