When we are on a live call with livekit flutter ap...
# ask-ai
b
When we are on a live call with livekit flutter app, and we keep the app in background and play video or take call and then we come back we arent able to hear anyone and nor they are able to hear me, even if we resubscribe all audio again and useroom.startAudio
t
Thanks for reaching out, Manish. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thanks — I’m responding about the audio cutting out after backgrounding in your LiveKit Flutter app. Quick checklist and next steps so I can help narrow this down: 1. Which platform(s) does this happen on — iOS, Android, or both? 2. Do you have background audio enabled? ◦ iOS: Is Background Modes → Audio enabled in Xcode / Info.plist? 1. Do you see any errors or ICE/connection state changes in logs when you return to foreground? 2. When you return to foreground, does: ◦ the local mic track show as published in your participant list/events? ◦ the remote participants’ tracks show as subscribed (but silent), or do subscriptions drop? 1. How are you calling recovery now? (You mentioned resubscribing and
useroom.startAudio
— are you also re-establishing the Room/PeerConnection or re-publishing tracks?) 2. Device model, OS versions, and LiveKit Flutter SDK version. What I recommend trying next (pick whichever fits your app): • Ensure iOS background-audio entitlement is set if you need audio while backgrounded. • On app resume, check ICE/PC state and if disconnected, reconnect the Room (call Room.connect or recreate the Room/PC) and re-publish tracks. • If ICE is still connected but audio is silent, explicitly stop and re-create the local audio track, then publish it again. • Log WebRTC/ICE states and track muted/enabled flags to confirm whether audio transport or just routing is affected. Send me the answers to 1–6 and any logs you can capture when resuming; I’ll propose exact code snippets for your recovery flow. Sources: Enhanced noise cancellation | LiveKit docs | Flutter quickstart | LiveKit docs | Camera & microphone | LiveKit docs | Swift quickstart | LiveKit docs | client-sdk-flutter | livekit/livekit_composite | DeepWiki
b
1. Which platform(s) does this happen on — iOS 2. Do you have background audio enabled? ◦ iOS: Is Background Modes → YES 3. Do you see any errors or ICE/connection state changes in logs when you return to foreground ---> No errors I see 4. When you return to foreground, does: ◦ the local mic track show as published in your participant list/events -- i just unsubsribe when i go to foreground ◦ the remote participants’ tracks show as subscribed (but silent), or do subscriptions drop? 5. How are you calling recovery now? I am using startAudio and alo resubscribing to all audio tracks 6. Device model, OS versions, and LiveKit Flutter SDK version-- Happens in Iphone IOs 18 and 26, Livekit version is latest
t
Thanks — I’m responding to your iOS-specific report where backgrounding (Background Modes → Audio enabled) then resuming leaves audio silent despite calling
startAudio
and re-subscribing. Likely cause • iOS is interrupting or changing the native audio session / routing or the WebRTC transport; simply re-subscribing or calling
startAudio
may not reinitialize the native AVAudioSession or peer connection state. Actionable steps to try now 1. On app resume, explicitly reconfigure and activate AVAudioSession before restoring tracks: ◦ Set category to
playAndRecord
with
.defaultToSpeaker
and activate the session. ◦ Example flow (pseudo): ▪︎ configure AVAudioSession: setCategory(.playAndRecord, options: .defaultToSpeaker) ▪︎ try AVAudioSession.sharedInstance().setActive(true) 1. After AVAudioSession is active, recreate and re-publish the local audio track instead of only calling `startAudio`: ◦ Stop current local audio track if exists. ◦ Create a new local audio track (via LiveKit Flutter API) and publish it. ◦ Then re-subscribe to remote audio tracks / ensure remote subscriptions are enabled. 1. If ICE/PeerConnection appears connected but audio is silent, perform a lightweight renegotiate: ◦ Call your Room.disconnect() and then reconnect, or trigger a track replace / re-offer so the peer connection renegotiates. 1. Add lifecycle wiring in Flutter: ◦ On AppLifecycleState.paused: optionally pause UI but keep room active if you rely on background audio. ◦ On AppLifecycleState.resumed: run the AVAudioSession activation + track recreate + resubscribe/renegotiate sequence. 1. Add logs to confirm sequence: ◦ Log AVAudioSession category/active state, local track `isMuted`/`isEnabled`, and Room/PC ICE connection state when resuming. What I can help next • I can provide concrete Flutter + native iOS code snippets (Swift for AVAudioSession and Flutter-side sequence) if you want. • If you can share logs showing AVAudioSession state or LiveKit track publish events at resume, I can point to the exact spot to change. Would you like the Swift + Flutter code snippets to implement steps 1–3?
b
Yes
t
Responding with iOS + Flutter code snippets and a short step sequence to restore audio after returning from background. What to do (sequence) 1. On resume, activate/configure AVAudioSession (category .playAndRecord, option .defaultToSpeaker) and set it active. 2. Recreate the local audio track (stop existing track, create new one) and publish/replace it on the Room. 3. If audio still silent, trigger a lightweight renegotiation (replaceTrack or disconnect/reconnect). 4. Add lifecycle hooks in Flutter to run this sequence on AppLifecycleState.resumed and log AVAudioSession + Room/track states. iOS (Swift) — AVAudioSession helper
Copy code
import AVFoundation

func configureAndActivateAudioSession() throws {
    let session = AVAudioSession.sharedInstance()
    try session.setCategory(.playAndRecord, options: [.defaultToSpeaker, .allowBluetooth])
    try session.setMode(.voiceChat)
    try session.setActive(true, options: [])
}

func deactivateAudioSession() {
    let session = AVAudioSession.sharedInstance()
    try? session.setActive(false, options: [])
}
Flutter side — lifecycle wiring (Dart)
Copy code
import 'package:flutter/widgets.dart';
import 'package:livekit_client/livekit_client.dart';
import 'package:flutter/services.dart';

class MyAppLifecycleHandler extends WidgetsBindingObserver {
  final Room room;
  static const platform = MethodChannel('com.example.app/audio');

  MyAppLifecycleHandler(this.room);

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      _onResume();
    }
  }

  Future<void> _onResume() async {
    // 1) Ensure native AVAudioSession is configured
    try {
      await platform.invokeMethod('configureAudioSession');
    } catch (e) {
      print('configureAudioSession error: $e');
    }

    // 2) Recreate local audio track and publish/replace
    try {
      final localParticipant = room.localParticipant;
      if (localParticipant == null) return;

      // stop existing audio tracks
      for (var pub in localParticipant.audioTracks) {
        await pub.stopTrack(); // or stop the underlying track if available
      }

      // create new track
      final newTrack = await LocalAudioTrack.createTrack();
      await localParticipant.publishTrack(newTrack);

      // 3) Ensure subscriptions are enabled for remote audio
      for (var p in room.participants.values) {
        for (var sub in p.audioTracks) {
          if (sub.subscriptionStatus != SubscriptionStatus.subscribed) {
            await sub.setSubscribed(true);
          }
        }
      }
    } catch (e) {
      print('audio restore error: $e');
    }

    // 4) Optionally check ICE / connection state and reconnect if needed
    if (room.connectionState != ConnectionState.connected) {
      try {
        await room.disconnect();
        // reconnect flow depends on your app - obtain token and call connect
      } catch (e) {
        print('reconnect error: $e');
      }
    }
  }
}
Android/iOS bridge — Swift method channel handler
Copy code
// AppDelegate.swift
import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  private let channelName = "com.example.app/audio"

  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
    let audioChannel = FlutterMethodChannel(name: channelName, binaryMessenger: controller.binaryMessenger)

    audioChannel.setMethodCallHandler { (call: FlutterMethodCall, result: @escaping FlutterResult) in
      if call.method == "configureAudioSession" {
        do {
          try configureAndActivateAudioSession()
          result(nil)
        } catch {
          result(FlutterError(code: "AUDIO_ERROR", message: error.localizedDescription, details: nil))
        }
      } else {
        result(FlutterMethodNotImplemented)
      }
    }

    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
Notes and tips • Use
.voiceChat
mode and
.allowBluetooth
option if Bluetooth headsets are used. • Replacing the track is usually lighter than full reconnect; prefer
localParticipant.replaceTrack(...)
if your SDK exposes it. • Log AVAudioSession.active, AVAudioSession.category, Room connectionState, and local track publish events to verify steps. • If you still see silent audio with Room.connected and tracks published, try a full reconnect (disconnect + connect) as a fallback. Would you like a ready-to-drop-in Flutter plugin example that covers full reconnect and track replace flows for your app?