← Back to posts Cover image for Mastering Audio Focus: Building Flutter TTS Apps That Respect User Music

Mastering Audio Focus: Building Flutter TTS Apps That Respect User Music

· 3 min read
Weekly Digest

The Flutter news you actually need

No spam, ever. Unsubscribe in one click.

Chris
By Chris

Text-to-speech in Flutter feels simple until the user is already listening to music. A navigation prompt stops the song, ducking never happens, or the track does not come back to normal volume. The problem is usually not the TTS engine itself; it is missing audio focus policy.

Common mistakes:

  • Requesting transient exclusive focus for every prompt.
  • Forgetting to abandon focus when speech stops, fails, or is canceled.
  • Letting prompts overlap.
  • Assuming the speak() future means audio finished.
  • Ignoring interruption callbacks from phone calls or other apps.

For short prompts, use transient ducking. On Android, this tells the system: “I need the audio route, but other audio should continue at lower volume.” Use transient focus when music should pause and resume. Use transient exclusive focus only for recording or very urgent prompts.

Here is a practical coordinator using flutter_tts and audio_session.

import 'dart:async';
import 'package:audio_session/audio_session.dart';
import 'package:flutter_tts/flutter_tts.dart';

class VoicePromptCoordinator {
  final _tts = FlutterTts();
  final _queue = <String>[];
  Completer<void>? _current;
  bool _speaking = false;

  Future<void> init() async {
    final session = await AudioSession.instance;

    await session.configure(const AudioSessionConfiguration.speech());
    await session.setAudioFocusGain(AudioFocusGain.transientMayDuck);

    await session.setAudioInterruptionCallback((event) async {
      if (event.type == AudioInterruptionType.pause ||
          event.type == AudioInterruptionType.unknown) {
        _queue.clear();
        await _tts.stop();
      }
    });

    await _tts.setCompletionHandler(_finish);
    await _tts.setCanceledHandler(_finish);
    await _tts.setErrorHandler((_) => _finish());
  }

  Future<void> speak(String text) async {
    if (text.trim().isEmpty) return;

    _queue.add(text);
    await _processQueue();
  }

  Future<void> _processQueue() async {
    if (_speaking || _queue.isEmpty) return;

    _speaking = true;
    final session = await AudioSession.instance;

    final gained = await session.setAudioFocus();
    if (!gained) {
      _speaking = false;
      return;
    }

    if (_queue.isEmpty) {
      await session.setAudioFocus(false);
      _speaking = false;
      return;
    }

    final text = _queue.removeAt(0);
    _current = Completer<void>();

    try {
      await _tts.speak(text);
      await _current!.future;
    } finally {
      await session.setAudioFocus(false);
      _speaking = false;
      _current = null;
      await _processQueue();
    }
  }

  void _finish() {
    final completer = _current;
    if (completer != null && !completer.isCompleted) {
      completer.complete();
    }
  }
}

This pattern keeps focus ownership explicit: request focus, speak, wait for completion, release focus, then process the next prompt.

For longer prompts, switch from AudioFocusGain.transientMayDuck to AudioFocusGain.transient. That stops background music while the prompt plays, then resumes it afterward.

Bluetooth can also clip the first syllable while the route settles. Do not fix this by increasing speech volume. Add a short pre-roll after gaining focus:

await session.setAudioFocus();
await Future.delayed(const Duration(milliseconds: 60));
await _tts.speak(text);

If that is not enough, play a 50–100 ms silent audio file through the same route before the prompt. Keep it short; users notice delay faster than they notice tiny clipping.

Interruptions matter too. If a phone call starts, stop the current prompt and discard stale queue items. Do not assume the user wants your navigation cue after they answer a call.

A few final checks:

  • Configure the audio session before initializing TTS.
  • Use a queue so prompts do not fight each other.
  • Always release focus in finally.
  • Test with Music, Spotify, and a Bluetooth headset.
  • If prompts can happen in the background, declare the iOS audio background mode and test suspended-state behavior.

Respectful TTS is not just about voice quality. It is about owning the audio route briefly and giving it back cleanly.

This blog is produced with the assistance of AI by a human editor. Learn more

Related Posts

Cover image for Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Choosing the Right Storage for Flutter: Beyond SharedPreferences for Persistent Data

Developers frequently struggle with persistent storage in Flutter, especially when dealing with OS-level backups and app reinstalls. This post will clarify the nuances of different storage solutions like `SharedPreferences`, `path_provider`, and `flutter_secure_storage`, focusing on how to correctly manage data lifetimes (per-install vs. per-user) and avoid issues like device IDs migrating to new phones or data being unexpectedly backed up.

Cover image for Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Optimizing Flutter UI Performance: Solving `ImageFiltered` Lag and Smooth Blurring

Flutter's `ImageFiltered` can cause significant lag when blurring large or frequently changing content like text. This post will explain the performance bottlenecks, provide solutions like caching blurred outputs with `RepaintBoundary` or `SnapshotWidget`, and offer practical tips to ensure smooth UI effects without sacrificing frame rates.