Skip to main content

voxera_calls_kit 0.2.1 copy "voxera_calls_kit: ^0.2.1" to clipboard
voxera_calls_kit: ^0.2.1 copied to clipboard

One-to-one voice and video calls for Flutter on Voxera: ringing, answering, camera and speaker controls, and ready-made call screens.

voxera_calls_kit #

One-to-one voice and video calls for Flutter on Voxera: ringing, answering, camera and speaker controls, and ready-made call screens.

It rings on the kit's own screen while the app is open, and on the system's call screen when the app is in the background or closed. Switching a voice call to video comes in a later version.

Setup #

Turn on signaling and the call types you need for your project in the console.

Android #

Add this to android/app/src/main/AndroidManifest.xml. Without it, a call can lose the microphone and camera when the screen turns off.

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CAMERA" />
<application>
  <service
      android:name="io.voxera.media.plugin.VoxeraMediaForegroundService"
      android:exported="false"
      android:foregroundServiceType="microphone|camera" />
</application>

iOS #

Add NSMicrophoneUsageDescription and NSCameraUsageDescription to Info.plist, and turn on the audio background mode. permission_handler also needs PERMISSION_MICROPHONE=1 and PERMISSION_CAMERA=1 in your Podfile.

Use #

Create one controller when the user signs in, and go online:

final calls = VoxeraCallController(
  config: const VoxeraCallConfig(
    baseUrl: 'https://your-engine.example.com',
    appId: 'your-app-id',
    appKey: 'your-app-key',
  ),
  userId: user.id,
  userName: user.name,
);
await calls.connect();

For production, pass sessionProvider instead of appKey, and have your server mint the session.

Show the screens over your whole app:

MaterialApp(
  builder: (context, child) => VoxeraCallHost(
    controller: calls,
    child: child!,
  ),
);

Place a call:

try {
  await calls.startCall('other-user', type: VoxeraCallType.video);
} on VoxeraCallException catch (e) {
  // e.kind: microphoneDenied, alreadyOnCall, callsDisabled, notConnected, ...
}

Incoming calls ring on their own while the controller is connected. To build your own screens, listen to the controller and read phase, call, endReason, isMicOn and the rest, then call accept, decline, hangUp, setMicOn, setCameraOn, switchCamera and setSpeakerOn.

Dispose the controller when the user signs out.

Change the words with VoxeraCallStrings, the colors with VoxeraCallTheme, and the picture with avatarBuilder.

Rules from your server #

Calls are ordinary calls unless your server says otherwise. Give your project a call check URL in the console, and the engine asks your server before each call rings. Your server answers:

  • {"allow": true}: an ordinary call.
  • {"allow": true, "max_duration_seconds": 180}: the call ends 180 seconds after it is answered.
  • {"allow": false, "reason": "blocked", "message": "You can't call this person"}: refused.

A refused call throws VoxeraCallErrorKind.notAllowed, with your server's message. The engine's docs (call-check-and-limits.md) have the full contract.

Calls with a time limit #

calls.call?.timeLimit;     // the call's length, null for an ordinary call
calls.remaining;           // ValueListenable<Duration?>, counts down every second
calls.timeWarnings.listen((left) {
  // 60 and 15 seconds before the end, by default: offer more time.
});

Only your server can add time, with the engine's extend endpoint. Both sides then see the new time. The call screen shows the time left; pass showTimeLeft: false to draw your own. A call that runs out ends with VoxeraCallEndReason.timeLimit.

Your own buttons on the call screen #

VoxeraCallHost(
  controller: calls,
  overlayBuilder: (context, controller) => Align(
    alignment: Alignment.topRight,
    child: SafeArea(child: TextButton(onPressed: buyTime, child: const Text('More time'))),
  ),
  child: child!,
);

Answering without ringing #

For a call the user already agreed to in your app, such as a call request they accepted:

VoxeraCallConfig(
  // ...
  autoAccept: (call) => call.metadata is Map && acceptedRequests.contains((call.metadata as Map)['request_id']),
);

The caller puts the request in startCall(..., metadata: {...}). Have your call check confirm it, so nobody can skip the ringing by writing the same metadata.

Who is online #

await calls.watchPresence(['ana', 'sam']);
calls.presence.value; // {'ana': true, 'sam': false}, and updates as they come and go
await calls.unwatchPresence(['ana', 'sam']);

Turn on presence for your project in the console.

Choosing where audio plays #

With no headset, the call screen's button toggles the speaker. With Bluetooth or a wired headset connected, it opens the choices instead. To build your own:

final routes = calls.audioRoutes;
routes.available; // [VoxeraAudioRoute.speaker, VoxeraAudioRoute.bluetooth]
routes.current;   // VoxeraAudioRoute.bluetooth
await calls.setAudioRoute(VoxeraAudioRoute.speaker);

iOS only switches between the speaker and whichever device it prefers. So with a headset connected it does not offer the earpiece, and with two headsets it picks one. Android offers every route.

Showing the caller's picture #

final calls = VoxeraCallController(
  config: config,
  userId: 'sam',
  userAvatarUrl: 'https://cdn.example.com/sam.png',
);

It goes with each call this user places, to the kit's incoming screen and Android's ringing screen. It has to be https, or it is left out. CallKit has nowhere to show one, so iPhones see the picture only inside your app. Whoever you call downloads this picture, so if your users choose their own, host them yourself instead of allowing any address.

Use avatarBuilder on VoxeraCallHost to draw it yourself.

Past calls #

final history = await calls.callHistory(page: 1, perPage: 20);
history.first.peerDisplayName;
history.first.isOutgoing;
history.first.wasMissed;
history.first.duration;

The newest come first, and an empty list means there are no more. A user only ever gets their own calls.

Ringing when the app is closed #

Add your APNs and Firebase credentials to your project in the console first. Then:

// When the user signs in, and whenever Firebase replaces the token.
await calls.registerPush(fcmToken: await FirebaseMessaging.instance.getToken());
await VoxeraCalls.requestRingPermissions();

// When the user signs out.
await calls.unregisterPush();

Create the controller and call connect as early as you can after your app starts. That is how a call the user just answered on the system's screen gets connected.

Android #

Your app keeps its own Firebase setup and passes the messages on, from the foreground and the background. To tell the engine right away when a call is declined while your app is closed, also register a background handler. It needs no signed-in user, as the push brings a token that can decline that one call. Both have to be top-level functions:

@pragma('vm:entry-point')
Future<void> onBackgroundMessage(RemoteMessage message) async {
  await VoxeraCalls.handlePush(message.data);
}

@pragma('vm:entry-point')
Future<void> onBackgroundCallEvent(CallEvent event) async {
  await VoxeraCalls.handleBackgroundEvent(event, config: callConfig);
}

void main() {
  FirebaseMessaging.onBackgroundMessage(onBackgroundMessage);
  FirebaseMessaging.onMessage.listen((message) => VoxeraCalls.handlePush(message.data));
  VoxeraCalls.registerBackgroundHandler(onBackgroundCallEvent);
  // ...
}

Without the handler, the caller keeps hearing it ring until the call times out.

iOS #

iOS ends any app that gets a VoIP push and does not show a call straight away, so this part is in Swift. Turn on the Push Notifications capability and the voip and audio background modes, then copy AppDelegate.swift from the example. CallKit does not work in the Simulator, so test this on an iPhone. Add your engine's address to Info.plist as VoxeraBaseUrl, the same baseUrl as your VoxeraCallConfig. Four parts of the file matter:

  • It registers plugins in didFinishLaunchingWithOptions. A VoIP push can start your app with no scene at all, so the template's newer didInitializeImplicitFlutterEngine may never run. Keep the example's version, even in a new project.
  • It reads the push's call_id, caller_name, caller_identity and call_type, and puts call_id in extra as voxera_call_id.
  • It passes CallKit's audio session on to WebRTC. Without this a call connects with no sound.
  • It sends a decline to the engine itself, as a VoIP push does not start Dart. Without this, or without VoxeraBaseUrl, a caller hears it ring until the call times out if the user declines while your app is closed.

Pass your Firebase messages to VoxeraCalls.handlePush on iOS too, and add the remote-notification background mode so they reach the app in the background. They stop the ringing when the caller gives up or another device answers. Calls ring without Firebase, but only stop when CallKit times out.

registerBackgroundHandler does nothing on iOS, where the Swift above does that job.

Outgoing calls on iOS #

Set outgoingOnSystemScreen: true on VoxeraCallConfig to put outgoing calls on CallKit as well, for the system's call screen and Recents. It needs the AppDelegate.swift above. It is off by default until it has been tested on real iPhones. Tapping a call in Recents opens your app, but does not place the call again.

Permissions #

Ask for the microphone, and the camera if you offer video, before the first call comes in. On a locked phone nobody can answer the prompt, and a call answered without the microphone is declined.

Minimizing #

The arrow on the call screen moves the call to a floating window, so the user can go on using your app. Tap the window to go back, or drag it to either side. VoxeraCallHost draws it for you. If your app has a VoxeraMiniOverlayHost for rooms, leave it in: there is still only one window. To do it from your own code, call minimizeCall and restoreCall.

Android's back button still acts on your app's page under the call screen, not on the call.

System window on Android #

A video call can shrink to a system window when the user leaves your app, on Android 12 and later. There is no such window on iOS yet, where the call goes on with sound only. To turn it on, pass minimize: const VoxeraCallMinimizeConfig(enableOSPip: true) in VoxeraCallConfig, and declare it on your activity:

<activity
    android:name=".MainActivity"
    android:supportsPictureInPicture="true"
    android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|screenLayout|density|uiMode">

Calls and rooms in the same app #

Only one call or room runs at a time. Placing or answering a call leaves the room the user is in, and joining a room ends the call. A call that only rings, is refused or is declined does not touch the room.

The audio engine is set up once per app run, for whichever comes first. An app that opens a room before its first call keeps the room's audio settings during calls, and the other way around. Decide which matters more, and open that one first.

0
likes
140
points
116
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

One-to-one voice and video calls for Flutter on Voxera: ringing, answering, camera and speaker controls, and ready-made call screens.

Homepage

Topics

#calling #video-call #webrtc #realtime

License

MIT (license)

Dependencies

flutter, flutter_callkit_incoming, permission_handler, voxera_media_client, voxera_room_core, voxera_signaling

More

Packages that depend on voxera_calls_kit