utd_audio_room_kit 3.16.2
utd_audio_room_kit: ^3.16.2 copied to clipboard
Real-time live audio room for Flutter: seat management, real-time chat, mic/speaker controls, speak requests, moderation, and minimize/PiP.
UTD Audio Room Kit #
A Flutter package for building live audio-room experiences, powered by a real-time audio engine and the UTD Stream Engine. It is a drop-in prebuilt live-audio-room solution: give it the required data and you get a fully interactive room — seats, chat, mic/speaker controls, seat actions, member list, speak requests, and moderation — with no extra UI code.
Echo/noise fix needs one line in your app: a tagged
flutter_webrtcoverride (v1.4.0-utd.1). Without it everything still works, with the platform's own echo canceller. See flutter_webrtc override under Installation / Getting started.
Features #
- Drop-in room UI — a complete, interactive room from required data alone.
- Seat management — take, leave, switch, lock, unlock, kick, mute, swap.
- Built-in seat actions — tap a seat to take/leave it; host/admin get a moderation sheet (mute, kick, lock, invite).
- Speak requests — audience apply-to-speak; host approve/reject queue with a live badge.
- Member list — participants with host actions (mute, kick, invite, ban, promote/demote).
- Media controls — microphone & speaker with reactive state (Bluetooth-preferring routing).
- Real-time chat — data-channel messages with batching and dedup.
- Reconnection — tiered: light sync (<15s), full sync (<60s), default force-exit (>60s).
- Minimize / PiP — minimize to a floating overlay; optional Android OS Picture-in-Picture.
- Theming & i18n —
UTDRoomTheme(colors) +UTDRoomStrings(EN/AR built in) without replacing widgets. - Full customization — replace any section (header, messages, controls, background, seats) with your own widgets.
Installation #
dependencies:
utd_audio_room_kit: ^3.14.0
The package is on pub.dev; do not use a path: dependency.
flutter_webrtc override (recommended for apps that publish the microphone) #
The echo/noise fix in utd_media_client uses an option that only exists in our fork of the
flutter_webrtc plugin. Without the override the app still builds and works; it simply falls back
to the platform's own echo canceller. To get the fix, pin the fork to a tagged version in your app's
pubspec.yaml (the tag never moves, so a build does not change under you):
dependency_overrides:
flutter_webrtc:
git:
url: https://github.com/UTD-Stream-Engine/webrtc-utd.git
ref: v1.4.0-utd.1 # flutter_webrtc 1.4.0 + softwareVoiceProcessing
v1.4.0-utd.1 is flutter_webrtc 1.4.0 plus one added option, softwareVoiceProcessing (hardware echo
canceller and noise suppressor off, call-path microphone kept). Unknown options are ignored by the original
plugin, so removing the override later is safe. Measured on one live room, three phones, same build, before the
fork: 8-12 dB cancelled on one phone, none on another.
Audio engine setup (required) #
The native media engine is built once per process, and the first thing
that touches it decides its audio profile. Claim the media profile before any
screen runs — first line of main():
import 'package:utd_media_client/utd_media_client.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await UtdmClient.initialize(mediaAudioProfile: true);
runApp(const MyApp());
}
Without this, any earlier WebRTC touch (a camera preview, a video renderer,
device enumeration) locks the process into the call profile — earpiece
routing, call volume — and no later call can undo it. If you ever see
[UtdmClient] the media engine was already initialized in the console,
something ran before this line; report it to us with the log.
Platform setup #
iOS — add to ios/Runner/Info.plist:
<key>NSMicrophoneUsageDescription</key>
<string>Required for audio room participation</string>
For background audio + PiP, enable Background Modes → Audio, AirPlay, and Picture in Picture in Xcode.
Android — add to android/app/src/main/AndroidManifest.xml:
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
Set minSdkVersion to at least 21 (31+ for OS PiP).
Permissions #
When the user takes a seat, the kit asks for the microphone and, on Android, BLUETOOTH_CONNECT (only while their status is still
denied, and only once the room is connected and the app is in the foreground). It uses permission_handler, which runs one request
at a time: a second request made while a dialog is up fails with "A request for permissions is already running".
If your app asks for permissions of its own, possibly while the room is open, hand the kit your requester so that every dialog goes through one queue (3.16.0+):
UTDAudioRoom(
// …
config: UTDAudioRoomConfig(
// A Future<PermissionStatus> Function(Permission): your app's single place that calls permission.request().
requestPermission: (permission) => MyPermissions.ask(permission),
),
);
// Without the widget: controller.seatController.requestPermission = MyPermissions.ask;
Without it the kit asks by itself. Either way a failed request never stops the seat from being taken and never throws out of
takeSeat; the operating system asks for the microphone when publishing starts. Your requester must complete: the take waits for
it, and the kit's next permission request waits for it at most 60 seconds, then goes ahead.
Credentials — pass your appKey (no backend required) #
Ship
appId+appKey(the project's publishable app key, from the UTD console). The kit mints tokens directly from the engine withX-App-Key; the engine signs the returned per-useruser_tokenwith the projectserver_secretserver-side, so the secret never ships in the app. The kit then uses thatuser_tokenas theAuthorization: Bearerfor all in-room calls. No token server to stand up.
appKey is not the server_secret: it can't sign tokens or call the server-to-server API, and
it can be rotated on its own from the console. Treat a leak as a project-scoped incident (rotate +
ship a new build).
Type-first engine. The engine groups products by a per-request
type, not by credential — oneappId/appKeyworks for every type enabled on the project. This kit always mintstype: 'audio_room'onPOST /api/v1/token; the project just needsaudio_roomin its enabled types (set per project in the UTD console). The seat model below is theaudio_roommodel — unchanged. (Live video broadcasts are a separatelive_streamtype served by the standalone live kit; this package does not use it.)
Quick start (drop-in, no backend) #
import 'package:utd_audio_room_kit/utd_audio_room_kit.dart';
UTDAudioRoom(
appId: '<utd-app-id>',
appKey: '<utd-app-key>', // publishable; the kit mints tokens itself, no backend needed
userId: 'user123',
userName: 'John Doe',
roomId: 'room456',
roomOwnerId: 'owner789', // userId == roomOwnerId ⇒ this user is the host
);
With only this, the package renders: a dark background, the seat grid (avatars + names), a header (minimize + exit), the chat list, and a role-aware controls bar. Tapping a seat takes/leaves it; audience can apply to speak; host/admin get member-list, the speak-request queue, and per-seat moderation. A connect failure shows an error + retry instead of an endless spinner.
The host is detected as
userId == roomOwnerId; identities inadminIdsare treated as admins. By default a host/admin joins mic-on (autoHostMic) and is auto-seated onhostSeatIndexif the backend didn't seat them (autoSeatHost).
Fast first join (recommended) #
The room body and seats render as soon as the token arrives — the RTC connection finishes in the background. That makes the token round trip the only thing standing between the tap and a populated room, so two one-time integrations make the FIRST entrance of a session as fast as every later one:
1. Warm up when a join becomes likely (e.g. the rooms lobby opens). The very first
request of a process otherwise pays DNS + TLS to the token host inline (~100–300 ms on
mobile networks), plus cold device caches. Since 3.14.0 (not yet published to pub.dev) the call for a rooms list is
warmForRoomList():
// When the rooms list appears (call again on refresh: it only extends the window).
UTDRoomController.warmForRoomList();
// When the list closes (optional: it also stops after 45 s, or when the app is backgrounded).
UTDRoomController.stopWarmingRoomList();
It warms DNS + TCP + TLS of the token host and of the RTC edge (HEAD requests only: no token,
no room, no participant) and renews every 12 s while the list is up. The signal socket and ICE
cannot be opened before the tap, they depend on the join response. On a first launch pass
rtcUrl: 'wss://<your edge>' to name the edge; after any join the kit remembers it. The plain
UTDRoomController.warmUp() still works (one-shot). The first dial now gives up at 4 s per phase (was 7 s; retries keep 7 s). To measure, set UTDJoinTimeline.enabled = true:
one [JOIN_TT] summary ... line per join, also in release builds.
2. Prefetch the token at tap time, so the round trip overlaps the route navigation instead of starting after the room screen mounts:
final controller = UTDRoomController()
..initApi(appId: appId, appKey: appKey)
..registerModes(myModes);
final isHost = userId == roomOwnerId;
final seatParams = UTDAudioRoom.resolveTokenSeatParams(
layoutMode: layoutMode, isHost: isHost, modes: myModes);
final tokenFuture = controller.generateToken(
identity: userId, roomName: roomId, roomOwnerId: roomOwnerId,
role: isHost ? 'host' : 'audience', name: userName,
seatCount: seatParams.seatCount, seatMode: seatParams.seatMode,
hostSeat: seatParams.hostSeat, modeId: seatParams.modeId,
);
// ...navigate, then pass BOTH to the widget:
UTDAudioRoom(
// ...,
controller: controller,
tokenProvider: () => tokenFuture,
);
If the provider fails (or answers null) the widget asks it again twice (after 0.4 s and 1.2 s); if it still fails the join fails with the
provider's own error (onConnectError). Since 3.16.1 the widget no longer mints with the publishable appKey behind your back, because an
engine that refuses app_key minting answers that mint with a 403 that hides the real cause. Pass allowAppKeyFallback: true to get the
3.16.0 behavior back (only for a project that opted into no-backend minting).
Avatars are disk-cached after the first download, so only a fresh install pays for
them once. Serve resized CDN thumbnails (e.g. ?w=128) in the avatar URLs — the kit
caps the decode size but cannot shrink the bytes on the wire.
Constructor #
| Param | Required | Description |
|---|---|---|
appId |
✅ | UTD Stream Engine app id (public identifier, safe to ship) |
appKey |
✅ | Publishable app key — the kit mints tokens directly from the engine (no backend). |
userId |
✅ | Local user identity |
userName |
✅ | Display name |
roomId |
✅ | Room to join/create |
roomOwnerId |
✅ | Owner identity (host detection + owner-only actions) |
adminIds |
– | Identities to request the admin role for |
layoutMode |
– | Mode id to use (default '3' = 9 seats); see Layout modes |
modes |
– | Custom UTDRoomModes to register |
config |
– | UTDAudioRoomConfig (see below) |
controller |
– | Reuse an existing UTDRoomController (e.g. after minimize) |
onControllerReady |
– | Get the controller (wire navigatorKey, minimize, etc.) |
onConnectionChanged |
– | (bool isConnected) |
onSeatTap |
– | Override the built-in seat action sheet |
onSeatChanged |
– | (List<SeatState> seats) |
onConnectError |
– | Override the built-in connect-error view |
onError |
– | (code, message): stable error code and end-user text in the app's language; called in addition to onConnectError |
Configuration (UTDAudioRoomConfig) #
UTDAudioRoom(
// …required data…
config: UTDAudioRoomConfig(
// behavior
showControlsBar: true,
showSeatNames: true, // render occupant names under seats
enableMinimize: true,
turnOnMicrophoneWhenJoining: false,
useSpeakerWhenJoining: true,
hostSeatIndex: 0,
autoHostMic: true, // host/admin joins mic-on
autoSeatHost: true, // host auto-takes hostSeatIndex if empty
useDefaultBackground: true, // paints theme.background when no backgroundWidget
// theming & strings
theme: UTDRoomTheme(), // or UTDRoomTheme().copyWith(primary: …)
strings: UTDRoomStrings.ar(), // null ⇒ English
// user attributes shared with others (name/avatar are read on seats)
userInRoomAttributes: {'avatar': 'https://…', 'name': 'John'},
// section overrides (null ⇒ built-in default)
headerWidget: null,
messagesWidget: null,
controlsBarWidget: null,
backgroundWidget: null,
foregroundWidget: null,
pkWidget: null,
// seat builders (null ⇒ built-in default avatar/name)
seatBuilder: null,
avatarBuilder: null,
emptySeatBuilder: null,
lockedSeatBuilder: null,
// permissions (null ⇒ the kit asks by itself; see "Permissions")
requestPermission: null,
),
);
Every built-in default is off when you override it — supplying a controlsBarWidget,
avatarBuilder, onSeatTap, etc. fully replaces the corresponding default.
Theming & localization #
UTDRoomTheme is an all-defaulted color set (dark by default, so the white default content
is never invisible). UTDRoomStrings.en() / .ar() cover every default label; pass your own
UTDRoomStrings(...) to translate or relabel:
config: UTDAudioRoomConfig(
theme: const UTDRoomTheme().copyWith(primary: Colors.teal, background: const Color(0xFF101010)),
strings: UTDRoomStrings.ar(),
);
Controller API #
onControllerReady gives you a UTDRoomController for programmatic control:
final c = controller;
// Seats
await c.seatController.takeSeat(0, c.localIdentity!);
await c.seatController.leaveSeat(c.localIdentity!);
await c.seatController.lockSeat(2, identity: c.localIdentity!);
// Why a take/move returned false because of the connection (null otherwise)
// code: 'connecting' (still dialing after the wait) | 'not_connected' (session ended)
final err = c.seatController.lastSeatError.value;
c.seatController.connectWait = const Duration(seconds: 8); // default
// Speak requests
await c.requestToSpeak();
await c.approveSpeakerRequest(requestId);
await c.inviteToSpeak(targetId, seatIndex: 3);
// Roles & bans (gated server-side)
await c.changeRole(targetIdentity: id, role: 'admin'); // OWNER-only (403 otherwise)
await c.banUser(id, reason: '…'); // host/admin-gated
// Media
await c.mediaController.toggleMicrophone();
// Reactive state
c.seatController.seats; // ValueNotifier<List<SeatState>>
c.seatController.pendingRequests; // ValueNotifier<List<SpeakerRequest>>
c.activeSpeakers; // ValueNotifier<Set<String>>
c.participantsStream; // Stream<List<UTDParticipant>>
Seat actions while the connection is re-dialing #
takeSeat and moveSeat wait for a connecting / reconnecting session for up to seatController.connectWait
(default 8 s) before asking the engine, so a brief network blip does not fail the tap. They still return
Future<bool>. When one returns false for a connection reason, seatController.lastSeatError.value tells you why:
code |
Meaning | message / messageAr |
Retry? |
|---|---|---|---|
connecting |
Still connecting after the wait; the engine was not asked | Connecting… please try again / جارٍ الاتصال… حاول مرة أخرى | yes |
not_connected |
Session ended (disconnected / error); the engine was not asked | Not connected to the room / غير متصل بالغرفة | no, rejoin first |
Since 3.15.0 it also says what happened when the engine WAS asked:
code |
Meaning | Retry? |
|---|---|---|
conflict |
The engine answered 409 and it is a real refusal (seat taken, locked, someone got there first) | no, pick another seat |
timeout |
No answer in time, also after the kit repeated the request. The result is unknown; the kit resyncs the seats | yes |
engine_busy |
The engine answered 5xx or 429, also after the repeats | yes, shortly |
permissions_pending |
takeSeat returned true, the user is seated, but the microphone permission did not reach the media server even after the kit asked the engine to write it again. Clears by itself if it arrives later |
wait, or leave and take again |
The kit repeats a take / move / leave that got no answer or a 5xx (up to two more sends, inside 14 s), always with the
same Idempotency-Key header, so an engine that knows the header never does the work twice. The 14 s limit
caps the whole action: a repeat's network timeout is cut to the time left. 408 is repeated like a 5xx (the one 4xx that is). Older engines ignore the header; if the first send had
actually run and the repeat meets 409 Already seated, a take counts that as success after confirming with the
seat list. A seat the host muted on purpose never reports permissions_pending.
lastSeatError is null after a success and after a refusal that has no code of its own (banned, role not allowed,
Seat is reserved). The constants are in UTDSeatErrorCode. The built-in seat sheet shows
UTDRoomStrings.seatConnecting for connecting.
Permission dialogs. The kit asks for the microphone (and, on Android, Bluetooth) only when you take a seat, only after the room is connected, and only while the app is in the foreground. A dialog raised during the connect pauses the app in the middle of the media handshake and the room can end up connected with no audio. If the app is in the background when the take happens the dialog is skipped; publishing asks the OS by itself.
Echo and call mode. The kit keeps the speaker on the media audio profile on Android (MODE_NORMAL), like the
listeners: a room is never a phone call. This needs utd_media_client ^2.10.0.
Staying alive in the background #
A voice room keeps working when the app goes to the background: the kit runs an Android foreground service (a low-importance
notification) while the user is in the room, as mediaPlayback while they listen and microphone|mediaPlayback while they are on the
microphone, and stops it when they leave. The limit is 10 hours in the background (UTDForegroundServiceConfig.maxDuration); then the
kit takes the user out of the room and calls controller.onBackgroundLimitReached.
It also stays up while the kit re-establishes a dropped session (stopping it there would make Android 14 refuse the restart from the
background), and goes with the recovery: when the recovery ends, or gives up, with the microphone off, it stops (the SDK keeps it 20 s
after a recovery so the microphone can come back first). The plugin's manifest entries are merged into your app automatically; an app
that targets API 34 must complete the foreground-service declaration in the Play Console or remove them with tools:node="remove".
UTDAudioRoomConfig(foregroundService: UTDForegroundServiceConfig(title: ..., text: ..., iconName: ...)) changes the notification;
UTDForegroundServiceConfig.disabled turns it off if your app has its own service. On iOS add the audio background mode. The
manifest, the runtime permissions, the Play Console declaration and a test checklist are in the SDK's
doc/staying-alive-in-the-background.md.
Minimize / PiP #
Wrap your app with UTDMiniPopScope and mount UTDMiniOverlayPage at the root, then
configure minimize in onControllerReady:
onControllerReady: (controller) {
controller.navigatorKey = navKey; // for default dialogs
controller.minimize.configure(
UTDMinimizeConfig(
enableOSPip: true,
onClose: () => myExitRoom(),
),
);
},
Layout modes #
The package ships one default mode (id: '3', 9 seats, 3×3). Register custom layouts via
modes and select with layoutMode:
UTDAudioRoom(
layoutMode: 'party',
modes: const [
UTDRoomMode(id: 'party', seatCount: 8, rows: [[0,1,2,3],[4,5,6,7]]),
],
);
SDK or UIKit? #
Both are the same product on the same engine; pick by who draws the screen.
utd_stream_sdk (headless) |
utd_audio_room_kit (this package) |
|
|---|---|---|
| You get | sessions, reactive state, actions; no widgets | UTDAudioRoom (a finished room screen), UTDRoomController, seat grid, chat, sheets, minimize / PiP |
| You build | the whole interface | only what you want to replace (config, theme, strings, builders) |
| Choose it when | you have your own design system, or no Flutter UI at all in the room | you want a working room in an afternoon and to restyle it |
They do not exclude each other: the kit runs on the SDK's logic. Recovery after a drop, user-token renewal, quality
reports, seat actions and the speaker / ban / role / chat-lock calls (UTDRoomOps) are the SDK's code; the kit adds the
widgets, the media session and its own HTTP stack. So behavior is the same in both, and a fix in the SDK reaches the kit.
What stays your decision. An app can use the SDK's UTDStreamClient for a call screen and this kit for the room,
but should not run an SDK session and the kit on the SAME identity in the same room: each keeps its own connection
(and reports its own quality samples) until the kit runs on the SDK's session itself, which is not part of 3.15.0.
Architecture #
UTDRoomController
├── (real-time engine) — connection & lifecycle (internal)
├── UTDSeatController — seat state (ValueNotifier) + speak requests
├── UTDMediaController — mic / speaker
├── UTDChatController — data-channel chat
└── UTDMinimizeController / UTDPipController
Inside the controller the work is split into small classes, one job each (internal, not exported; the public getters and
callbacks of the controller are unchanged): UTDRoster (participants, roles, admins), UTDMicTracker (mute icons and
the recovery tick), UTDSessionWiring (engine signals), UTDHostActions (speaker flow, bans, roles, chat lock),
UTDKitApis (the API clients), UTDTokenSource (minting), UTDInvitationFlow (the invitation dialog and flow).
All state is exposed via ValueNotifier/Stream, so it integrates with any state-management
approach. See the Quick start snippet above for a minimal drop-in app.