Read chat replies aloud with word highlighting

An assistant reply gets Read aloud beside Copy; while it reads it becomes
Pause/Resume and Stop, one reply at a time app-wide. The spoken word is
highlighted in the rendered reply (across multi-part replies) and the
transcript scrolls only when that word leaves the viewport. Reading stops
when its chat closes or is swapped, another reply starts, or the app goes
to the background. Markdown is spoken as sentences; code blocks are
announced as "Code block.".

Speech goes through a SpeechEngine seam with a flutter_tts implementation
(Android, macOS, web; hidden on Linux) and a fake for tests. Settings has
a Read aloud section: a voice picker grouped by language (device language
first, a sample per voice), a rate slider and reset, saved per device.

flutter_tts has no Swift package, so macOS/iOS gain the CocoaPods
integration (Podfiles with the Runner deployment targets); Android
declares the TTS_SERVICE query. The capture fixture gains ?speech=fake.
This commit is contained in:
2026-11-13 01:29:04 +00:00
parent 26e68140fd
commit 6367cce68a
40 changed files with 2643 additions and 29 deletions
@@ -0,0 +1,112 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'speech_engine.dart';
/// [SpeechEngine] over the `flutter_tts` plugin (Android, Apple, web).
/// The plugin is created on first use so merely building the UI opens no
/// platform channel.
class FlutterTtsSpeechEngine extends SpeechEngine {
FlutterTts? _plugin;
SpeechVoice? _applied;
@override
bool get supported =>
kIsWeb ||
switch (defaultTargetPlatform) {
TargetPlatform.android ||
TargetPlatform.iOS ||
TargetPlatform.macOS ||
TargetPlatform.windows => true,
TargetPlatform.linux || TargetPlatform.fuchsia => false,
};
/// AVSpeechSynthesizer's normal rate is 0.5 on a 0..1 scale; Android's
/// TextToSpeech and the Web Speech API use 1.0 as normal.
bool get _appleScale =>
!kIsWeb &&
(defaultTargetPlatform == TargetPlatform.iOS ||
defaultTargetPlatform == TargetPlatform.macOS);
FlutterTts get _tts => _plugin ??= _create();
FlutterTts _create() {
final tts = FlutterTts();
tts.setStartHandler(() => onStart?.call());
tts.setPauseHandler(() => onPause?.call());
tts.setContinueHandler(() => onResume?.call());
tts.setCompletionHandler(() => onCompletion?.call());
tts.setCancelHandler(() => onCancel?.call());
tts.setErrorHandler((message) => onError?.call('$message'));
tts.setProgressHandler(
(utterance, start, end, _) => onProgress?.call(utterance, start, end),
);
return tts;
}
@override
Future<void> speak(String text) async => _tts.speak(text);
@override
Future<void> pause() async => _tts.pause();
@override
Future<void> stop() async => _tts.stop();
@override
Future<void> setRate(double rate) async =>
_tts.setSpeechRate(_appleScale ? (rate * 0.5).clamp(0, 1) : rate);
@override
Future<void> setVoice(SpeechVoice? voice) async {
if (voice == _applied) return;
if (voice != null) {
await _tts.setVoice({'name': voice.name, 'locale': voice.locale});
_applied = voice;
return;
}
if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) {
await _tts.clearVoice();
_applied = null;
return;
}
// Apple and web plugins cannot clear a chosen voice. After one was chosen
// in this run (a sample, or a setting that was reset) the device
// language's first voice stands in for the system default.
final device = PlatformDispatcher.instance.locale.languageCode;
final fallback = (await voices())
.where((item) => item.language == device.toLowerCase())
.firstOrNull;
if (fallback == null) return;
await _tts.setVoice({'name': fallback.name, 'locale': fallback.locale});
_applied = null;
}
@override
Future<List<SpeechVoice>> voices() async {
var voices = await _readVoices();
// Browsers load their voice list asynchronously after the first request.
for (var attempt = 0; kIsWeb && voices.isEmpty && attempt < 4; attempt++) {
await Future<void>.delayed(const Duration(milliseconds: 250));
voices = await _readVoices();
}
return voices;
}
Future<List<SpeechVoice>> _readVoices() async {
Object? raw;
try {
raw = await _tts.getVoices;
} on PlatformException {
return const [];
} on MissingPluginException {
return const [];
}
return [
for (final item in raw is List ? raw : const [])
if (item is Map && item['name'] != null && item['locale'] != null)
SpeechVoice(name: '${item['name']}', locale: '${item['locale']}'),
];
}
}
+4
View File
@@ -0,0 +1,4 @@
export 'speech_controller.dart';
export 'speech_document.dart';
export 'speech_engine.dart';
export 'speech_preferences.dart';
@@ -0,0 +1,265 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'flutter_tts_speech_engine.dart';
import 'speech_document.dart';
import 'speech_engine.dart';
import 'speech_preferences.dart';
enum SpeechState { idle, speaking, paused }
/// The app-wide reader: one reply speaks at a time. It notifies on state
/// changes; the spoken word moves on the separate, frequent [word].
class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
SpeechController({SpeechEngine? engine, SpeechPreferencesStore? store})
: engine = engine ?? FlutterTtsSpeechEngine(),
_store = store ?? const SharedSpeechPreferencesStore() {
WidgetsBinding.instance.addObserver(this);
this.engine
..onStart = _started
..onPause = (() => _set(SpeechState.paused))
..onResume = (() => _set(SpeechState.speaking))
..onCompletion = _ended
..onCancel = _ended
..onError = _failed
..onProgress = _progress;
}
final SpeechEngine engine;
final SpeechPreferencesStore _store;
SpeechState _state = SpeechState.idle;
String? _messageId;
SpeechDocument? _document;
Completer<void>? _stopping;
Future<void>? _restoring;
var _awaitingStart = false;
double _rate = defaultSpeechRate;
SpeechVoice? _voice;
bool saveFailed = false;
/// The range of the word being spoken in [document]'s text, or null.
final word = ValueNotifier<SpeechRange?>(null);
bool get supported => engine.supported;
SpeechState get state => _state;
String? get messageId => _messageId;
SpeechDocument? get document => _document;
double get rate => _rate;
SpeechVoice? get voice => _voice;
bool get isDefault => _rate == defaultSpeechRate && _voice == null;
/// Loads the saved voice and rate once.
Future<void> restore() => _restoring ??= _load();
Future<void> _load() async {
final saved = await _store.load();
if (saved == null) return;
_rate = saved.rate.clamp(minSpeechRate, maxSpeechRate);
_voice = saved.voice;
notifyListeners();
}
/// Reads reply [id] made of markdown [parts], stopping any other reading.
Future<void> read(String id, List<String> parts) async {
final document = speechDocumentFor(parts);
await stop();
await restore();
if (document.text.isEmpty) return;
await _speak(id, document, _voice);
}
/// Speaks a short sample in [voice] (or the chosen one) at the chosen rate.
Future<void> sample([SpeechVoice? voice]) async {
await stop();
await restore();
await _speak(
speechSampleId,
speechDocumentFor(['This is how replies will sound when read aloud.']),
voice ?? _voice,
);
}
Future<void> _speak(String id, SpeechDocument document, SpeechVoice? voice) {
_messageId = id;
_document = document;
_awaitingStart = true;
word.value = null;
_set(SpeechState.speaking);
return _guard(() async {
await engine.setRate(_rate);
await engine.setVoice(voice);
await engine.speak(document.text);
});
}
Future<void> pause() async {
if (_state != SpeechState.speaking) return;
_set(SpeechState.paused);
await _guard(engine.pause);
}
/// Continues a paused reply where it stopped; every platform resumes when
/// the paused utterance's text is spoken again.
Future<void> resume() async {
final document = _document;
if (_state != SpeechState.paused || document == null) return;
_set(SpeechState.speaking);
await _guard(() => engine.speak(document.text));
}
Future<void> stop() async {
if (_state == SpeechState.idle) return;
final stopping = _stopping = Completer<void>();
await _guard(engine.stop);
// Wait briefly for the platform's cancel so it cannot end the next reply
// and so web speech is idle before the next utterance is queued.
await stopping.future.timeout(
const Duration(milliseconds: 400),
onTimeout: () {},
);
if (identical(_stopping, stopping)) _stopping = null;
_clear();
}
/// Stops reading when the reply being read has an id under [scope].
Future<void> stopScope(String scope) async {
if (_messageId?.startsWith(speechScopePrefix(scope)) ?? false) {
await stop();
}
}
/// Sets the rate for the next reading; [save] false previews a slider drag.
Future<void> setRate(double value, {bool save = true}) async {
_rate = value.clamp(minSpeechRate, maxSpeechRate);
notifyListeners();
if (save) await _save();
}
Future<void> setVoice(SpeechVoice? value) async {
_voice = value;
notifyListeners();
await _save();
}
Future<void> reset() async {
_rate = defaultSpeechRate;
_voice = null;
notifyListeners();
await _save();
}
Future<void> _save() async {
saveFailed = !await _store.save((rate: _rate, voice: _voice));
notifyListeners();
}
Future<List<SpeechVoice>> voices() => engine.voices();
void _started() {
_awaitingStart = false;
if (_messageId != null) _set(SpeechState.speaking);
}
void _ended() {
final stopping = _stopping;
if (stopping != null) {
if (!stopping.isCompleted) stopping.complete();
return;
}
// A late cancel from the previous utterance must not end the new one.
if (_awaitingStart) return;
_clear();
}
void _failed(String message) {
if (message == 'interrupted' || message == 'canceled') return _ended();
final stopping = _stopping;
if (stopping != null && !stopping.isCompleted) stopping.complete();
_clear();
}
void _progress(String utterance, int start, int end) {
final document = _document;
if (document == null || _state == SpeechState.idle) return;
// After a resume a platform may speak only the remaining suffix.
final base = document.text.endsWith(utterance)
? document.text.length - utterance.length
: 0;
_awaitingStart = false;
word.value = (start: start + base, end: end + base);
}
Future<void> _guard(Future<void> Function() action) async {
try {
await action();
} catch (error) {
debugPrint('Read aloud failed: $error');
_clear();
}
}
void _set(SpeechState value) {
if (_state == value) return;
_state = value;
notifyListeners();
}
void _clear() {
_awaitingStart = false;
_messageId = null;
_document = null;
word.value = null;
_state = SpeechState.idle;
notifyListeners();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// Inactive is only a lost focus (a desktop window behind another, the
// Android shade); hidden and paused mean the app is in the background.
if (state == AppLifecycleState.hidden ||
state == AppLifecycleState.paused ||
state == AppLifecycleState.detached) {
unawaited(stop());
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
engine
..onStart = null
..onPause = null
..onResume = null
..onCompletion = null
..onCancel = null
..onError = null
..onProgress = null;
if (_state != SpeechState.idle) unawaited(engine.stop().catchError((_) {}));
word.dispose();
super.dispose();
}
}
/// The reader's id for the Settings voice sample.
const speechSampleId = 'settings-sample';
/// The id prefix for replies of one conversation (see [speechMessageId]).
String speechScopePrefix(String scope) => '$scope/';
/// A reply's id for the reader, unique across conversations.
String speechMessageId(String scope, String rowId) => '$scope/$rowId';
SpeechController? _speechController;
/// The app's single reader.
SpeechController get speechController =>
_speechController ??= SpeechController();
/// Replaces the app's reader (a fake engine in tests and capture fixtures);
/// null restores the platform one.
set debugSpeechController(SpeechController? controller) =>
_speechController = controller;
@@ -0,0 +1,171 @@
import '../ui/transcript/chat_markdown.dart';
import '../ui/transcript/chat_markdown_cache.dart';
typedef SpeechRange = ({int start, int end});
/// Where one spoken character came from: an offset into one markdown part.
typedef SpeechSource = ({int part, int offset});
/// A reply as spoken text, with the markdown source of every spoken character.
/// A reply can have several text parts; each is rendered by its own view, so
/// sources name the part as well as the offset within its trimmed text.
class SpeechDocument {
const SpeechDocument({
required this.text,
required this.parts,
required this.sources,
});
final String text;
/// The trimmed markdown of each part, in reading order.
final List<String> parts;
final List<SpeechSource> sources;
/// The index of the part whose markdown is [markdown], or -1.
int partOf(String markdown) => parts.indexOf(markdown.trim());
/// The source range in [part] that the spoken [range] covers, or null when
/// the spoken text there came from another part.
SpeechRange? sourceRange(int part, SpeechRange range) {
int? start;
int? end;
final last = range.end.clamp(0, sources.length);
for (var index = range.start.clamp(0, last); index < last; index += 1) {
final source = sources[index];
if (source.part != part) continue;
if (start == null || source.offset < start) start = source.offset;
if (end == null || source.offset + 1 > end) end = source.offset + 1;
}
return start == null ? null : (start: start, end: end!);
}
}
SpeechDocument markdownToSpeech(String markdown) =>
speechDocumentFor([markdown]);
/// Converts reply parts to natural speech: markup is dropped, blocks become
/// sentences, and a fenced code block is announced as "Code block." rather
/// than read out. Visible characters are located in order in the source, so
/// repeated words map to their own occurrence.
SpeechDocument speechDocumentFor(List<String> markdownParts) {
final parts = [
for (final part in markdownParts)
if (part.trim().isNotEmpty) part.trim(),
];
final builder = _SpeechBuilder();
for (var index = 0; index < parts.length; index += 1) {
builder.addPart(index, parts[index]);
}
return SpeechDocument(
text: builder.spoken.toString(),
parts: parts,
sources: builder.sources,
);
}
class _SpeechBuilder {
final spoken = StringBuffer();
final sources = <SpeechSource>[];
String _markdown = '';
var _part = 0;
var _cursor = 0;
void addPart(int part, String markdown) {
_part = part;
_markdown = markdown;
_cursor = 0;
for (final block in chatMarkdownCache.blocksFor(markdown)) {
switch (block) {
case MarkdownHeading(text: final text):
_visible(text);
case MarkdownParagraph(text: final text):
_visible(text);
case MarkdownQuote(lines: final lines):
lines.where((line) => line.trim().isNotEmpty).forEach(_visible);
case MarkdownList(items: final items):
items.forEach(_visible);
case MarkdownTable(header: final header, rows: final rows):
_phrase('Table.', _cursor);
[...header, ...rows.expand((row) => row)].forEach(_visible);
case MarkdownCode(code: final code):
_skipCode(code);
case MarkdownRule():
break;
}
}
}
/// Ends the previous sentence so blocks are not read as one run-on line.
void _sentenceBreak(int at) {
if (spoken.isEmpty) return;
if (!RegExp(r'[.!?:;]$').hasMatch(spoken.toString())) _write('.', at);
_write(' ', at);
}
void _write(String value, int at) {
spoken.write(value);
for (var index = 0; index < value.length; index += 1) {
sources.add((part: _part, offset: at));
}
}
void _phrase(String value, int at) {
_sentenceBreak(at);
_write(value, at);
}
void _visible(String blockText) {
final value = _plain(blockText).trim();
if (value.isEmpty) return;
final start = _markdown.indexOf(blockText, _cursor);
final blockStart = start < 0 ? _cursor : start;
final blockEnd = start < 0 ? _markdown.length : start + blockText.length;
_sentenceBreak(blockStart);
var search = blockStart;
for (var index = 0; index < value.length; index += 1) {
final character = value[index];
final found = search >= blockEnd
? -1
: _markdown.indexOf(character, search);
final inBlock = found >= 0 && found < blockEnd;
spoken.write(character);
sources.add((part: _part, offset: inBlock ? found : search));
if (inBlock) search = found + 1;
}
_cursor = start < 0 ? search : blockEnd;
}
void _skipCode(String code) {
final span = fencedCodeSpan(_markdown, _cursor, code);
_phrase('Code block.', span.start);
_cursor = span.end;
}
}
/// The source range of the fenced code block holding [code] that starts at or
/// after [cursor] (``` or ~~~ fences); an unclosed fence runs to its code's end.
SpeechRange fencedCodeSpan(String source, int cursor, String code) {
int find(String marker) => source.indexOf(marker, cursor);
final fences = [find('```'), find('~~~')].where((index) => index >= 0);
if (fences.isEmpty) return (start: cursor, end: cursor);
final opening = fences.reduce((a, b) => a < b ? a : b);
final marker = source.substring(opening, opening + 3);
final closing = source.indexOf(marker, opening + 3);
if (closing >= 0) return (start: opening, end: closing + 3);
final codeStart = source.indexOf(code, opening + 3);
return (
start: opening,
end: codeStart < 0 ? opening + 3 : codeStart + code.length,
);
}
String _plain(String value) => parseInline(value).map(_inlinePlain).join();
String _inlinePlain(MarkdownInline span) => switch (span) {
MarkdownPlain(text: final text) => text,
MarkdownInlineCode(text: final text) => text,
MarkdownStrong(spans: final spans) => spans.map(_inlinePlain).join(),
MarkdownEmphasis(spans: final spans) => spans.map(_inlinePlain).join(),
MarkdownLink(spans: final spans) => spans.map(_inlinePlain).join(),
};
@@ -0,0 +1,50 @@
import 'package:flutter/foundation.dart';
/// One platform voice. [locale] is a BCP 47 tag such as `en-GB`.
@immutable
class SpeechVoice {
const SpeechVoice({required this.name, required this.locale});
final String name;
final String locale;
/// The primary language subtag (`en` for `en-GB`), lower case.
String get language => locale.split(RegExp('[-_]')).first.toLowerCase();
@override
bool operator ==(Object other) =>
other is SpeechVoice && other.name == name && other.locale == locale;
@override
int get hashCode => Object.hash(name, locale);
}
/// The platform text-to-speech service the [SpeechController] drives.
///
/// [setRate] takes a multiplier where 1.0 is the platform's normal speed; an
/// implementation maps it onto its own scale. [onProgress] reports the word
/// being spoken as offsets into [utterance], the text the platform is actually
/// speaking (after a resume that can be a suffix of the text passed to
/// [speak]). Platforms without word boundaries never call it.
abstract class SpeechEngine {
/// Whether this platform can speak at all; the UI hides read aloud if not.
bool get supported;
VoidCallback? onStart;
VoidCallback? onPause;
VoidCallback? onResume;
VoidCallback? onCompletion;
VoidCallback? onCancel;
ValueChanged<String>? onError;
void Function(String utterance, int start, int end)? onProgress;
/// Speaks [text]. Called with the same text while paused, it resumes.
Future<void> speak(String text);
Future<void> pause();
Future<void> stop();
/// Selects [voice], or the platform default when null.
Future<void> setVoice(SpeechVoice? voice);
Future<void> setRate(double rate);
Future<List<SpeechVoice>> voices();
}
@@ -0,0 +1,62 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'speech_engine.dart';
const speechRateKey = 'pipelines.readAloud.rate.v1';
const speechVoiceNameKey = 'pipelines.readAloud.voiceName.v1';
const speechVoiceLocaleKey = 'pipelines.readAloud.voiceLocale.v1';
/// The normal speaking rate and the slider's bounds (a multiplier).
const defaultSpeechRate = 1.0;
const minSpeechRate = 0.5;
const maxSpeechRate = 2.0;
typedef SpeechPreferences = ({double rate, SpeechVoice? voice});
/// Device-local read-aloud settings.
abstract interface class SpeechPreferencesStore {
Future<SpeechPreferences?> load();
Future<bool> save(SpeechPreferences preferences);
}
class SharedSpeechPreferencesStore implements SpeechPreferencesStore {
const SharedSpeechPreferencesStore();
@override
Future<SpeechPreferences?> load() async {
try {
final prefs = await SharedPreferences.getInstance();
final name = prefs.getString(speechVoiceNameKey);
final locale = prefs.getString(speechVoiceLocaleKey);
return (
rate: prefs.getDouble(speechRateKey) ?? defaultSpeechRate,
voice: name == null || locale == null
? null
: SpeechVoice(name: name, locale: locale),
);
} catch (_) {
return null;
}
}
@override
Future<bool> save(SpeechPreferences preferences) async {
try {
final prefs = await SharedPreferences.getInstance();
final voice = preferences.voice;
final saved = [
await prefs.setDouble(speechRateKey, preferences.rate),
if (voice == null) ...[
await prefs.remove(speechVoiceNameKey),
await prefs.remove(speechVoiceLocaleKey),
] else ...[
await prefs.setString(speechVoiceNameKey, voice.name),
await prefs.setString(speechVoiceLocaleKey, voice.locale),
],
];
return !saved.contains(false);
} catch (_) {
return false;
}
}
}