import 'dart:async'; import 'package:flutter/widgets.dart'; import 'flutter_tts_speech_engine.dart' if (dart.library.js_interop) 'web_speech_engine.dart'; import 'speech_document.dart'; import 'speech_engine.dart'; import 'speech_preferences.dart'; import 'speech_reading.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]. /// /// It belongs to the app (see [speechController]), not to the conversation /// that started it: leaving that chat, switching panes or opening the list /// keeps the reply reading. It ends when stopped, when it finishes, when /// another reply starts, when its chat is closed or deleted ([stopScope]), /// and when the app goes to the background or closes. class SpeechController extends ChangeNotifier with WidgetsBindingObserver { SpeechController({SpeechEngine? engine, SpeechPreferencesStore? store}) : engine = engine ?? createSpeechEngine(), _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? _stopping; Future? _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(null); /// The conversation whose reply is reading (paused included), or null. /// It changes only when a reading starts, ends or its chat is renamed. final reading = ValueNotifier(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 restore() => _restoring ??= _load(); Future _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. /// [scope] is the reply's conversation (by default the part of [id] before /// its first `/`, see [speechMessageId]) and [title] its name, which the /// speaking indicator and the global Stop show. Future read( String id, List parts, { String? scope, String title = '', }) async { final document = speechDocumentFor(parts); await stop(); await restore(); if (document.text.isEmpty) return; await _speak( id, document, _voice, SpeechReading(scope: scope ?? speechScopeOf(id), title: title), ); } /// Speaks a short sample in [voice] (or the chosen one) at the chosen rate. Future sample([SpeechVoice? voice]) async { await stop(); await restore(); await _speak( speechSampleId, speechDocumentFor(['This is how replies will sound when read aloud.']), voice ?? _voice, null, ); } Future _speak( String id, SpeechDocument document, SpeechVoice? voice, SpeechReading? origin, ) { _messageId = id; _document = document; reading.value = origin; _awaitingStart = true; word.value = null; _set(SpeechState.speaking); return _guard(() async { await engine.setRate(_rate); final selected = voice ?? bestSpeechVoice( await engine.voices(), WidgetsBinding.instance.platformDispatcher.locale.languageCode, ); await engine.setVoice(selected); await engine.speak(document.text); }); } Future 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 resume() async { final document = _document; if (_state != SpeechState.paused || document == null) return; _set(SpeechState.speaking); await _guard(() => engine.speak(document.text)); } Future stop() async { if (_state == SpeechState.idle) return; final stopping = _stopping = Completer(); 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 belongs to conversation /// [scope]: the chat was closed or deleted. Future stopScope(String scope) async { if (reading.value?.scope == scope || (_messageId?.startsWith(speechScopePrefix(scope)) ?? false)) { await stop(); } } /// Follows a rename of the conversation being read. void retitle(String scope, String title) { final current = reading.value; if (current == null || current.scope != scope || current.title == title) { return; } reading.value = SpeechReading(scope: scope, title: title); } /// Sets the rate for the next reading; [save] false previews a slider drag. Future setRate(double value, {bool save = true}) async { _rate = value.clamp(minSpeechRate, maxSpeechRate); notifyListeners(); if (save) await _save(); } Future setVoice(SpeechVoice? value) async { _voice = value; notifyListeners(); await _save(); } Future reset() async { _rate = defaultSpeechRate; _voice = null; notifyListeners(); await _save(); } Future _save() async { saveFailed = !await _store.save((rate: _rate, voice: _voice)); notifyListeners(); } Future> 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 _guard(Future 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; reading.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(); reading.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'; /// The conversation part of a reader id made by [speechMessageId]. String speechScopeOf(String id) { final slash = id.indexOf('/'); return slash < 0 ? id : id.substring(0, slash); }