Merge branch 'worktree-agent-a69b1e8a6164ea62e'

This commit is contained in:
2026-12-01 21:05:51 +00:00
17 changed files with 737 additions and 17 deletions
@@ -4,7 +4,10 @@ import 'package:flutter_tts/flutter_tts.dart';
import 'speech_engine.dart';
/// [SpeechEngine] over the `flutter_tts` plugin (Android, Apple, web).
/// The platform engine off the web (the web uses `web_speech_engine.dart`).
SpeechEngine createSpeechEngine() => FlutterTtsSpeechEngine();
/// [SpeechEngine] over the `flutter_tts` plugin (Android, Apple, Windows).
/// The plugin is created on first use so merely building the UI opens no
/// platform channel.
class FlutterTtsSpeechEngine extends SpeechEngine {
@@ -2,7 +2,8 @@ import 'dart:async';
import 'package:flutter/widgets.dart';
import 'flutter_tts_speech_engine.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';
@@ -13,7 +14,7 @@ enum SpeechState { idle, speaking, paused }
/// changes; the spoken word moves on the separate, frequent [word].
class SpeechController extends ChangeNotifier with WidgetsBindingObserver {
SpeechController({SpeechEngine? engine, SpeechPreferencesStore? store})
: engine = engine ?? FlutterTtsSpeechEngine(),
: engine = engine ?? createSpeechEngine(),
_store = store ?? const SharedSpeechPreferencesStore() {
WidgetsBinding.instance.addObserver(this);
this.engine
@@ -0,0 +1,155 @@
import 'dart:async';
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:web/web.dart' as web;
import 'speech_engine.dart';
/// The platform engine on the web: the browser's Web Speech API directly.
SpeechEngine createSpeechEngine() => WebSpeechEngine();
/// [SpeechEngine] over `window.speechSynthesis` through `package:web`.
///
/// It replaces the flutter_tts web plugin, whose JS interop casts
/// (`event['charIndex'] as int`) and method-channel error payloads fail
/// under WebAssembly: word progress and error reports never arrived there.
/// The behaviour matches that plugin: speaking while paused resumes, and a
/// remote voice is kept alive with a pause/resume every 14 seconds (Chrome
/// stops a network voice after about 15 seconds of speech).
class WebSpeechEngine extends SpeechEngine {
web.SpeechSynthesisUtterance? _utterance;
web.SpeechSynthesisVoice? _voice;
double _rate = 1;
bool _paused = false;
Timer? _keepAlive;
@override
bool get supported => web.window.has('speechSynthesis');
web.SpeechSynthesis get _synth => web.window.speechSynthesis;
@override
Future<void> speak(String text) async {
if (text.isEmpty) return;
if (_paused && _utterance != null) {
_paused = false;
_synth.resume();
return;
}
final utterance = web.SpeechSynthesisUtterance(text)..rate = _rate;
final voice = _voice;
if (voice != null) {
utterance
..voice = voice
..lang = voice.lang;
}
_listen(utterance);
_utterance = utterance;
_paused = false;
_synth.speak(utterance);
}
void _listen(web.SpeechSynthesisUtterance utterance) {
bool current() => identical(_utterance, utterance);
utterance
..onstart = ((web.Event _) {
if (!current()) return;
onStart?.call();
if (!(utterance.voice?.localService ?? false)) _keepAliveWhileSpeaking();
}).toJS
..onend = ((web.Event _) {
if (!current()) return;
_finish();
onCompletion?.call();
}).toJS
..onpause = ((web.Event _) {
if (current() && _paused) onPause?.call();
}).toJS
..onresume = ((web.Event _) {
if (current() && !_paused) onResume?.call();
}).toJS
..onerror = ((web.SpeechSynthesisErrorEvent event) {
if (!current()) return;
_finish();
onError?.call(event.error);
}).toJS
..onboundary = ((web.SpeechSynthesisEvent event) {
if (!current() || event.name == 'sentence') return;
final text = utterance.text;
final start = event.charIndex.clamp(0, text.length);
onProgress?.call(text, start, _wordEnd(text, start, event.charLength));
}).toJS;
}
/// The end of the word at [start]: the browser's length when it reports
/// one, else the next space or punctuation (as flutter_tts did).
static int _wordEnd(String text, int start, int length) {
if (length > 0) return (start + length).clamp(start, text.length);
var end = start;
while (end < text.length && !RegExp(r'[\s,.!?]').hasMatch(text[end])) {
end++;
}
return end;
}
void _keepAliveWhileSpeaking() {
_keepAlive?.cancel();
_keepAlive = Timer.periodic(const Duration(seconds: 14), (_) {
if (_paused || _utterance == null) return;
_synth
..pause()
..resume();
});
}
void _finish() {
_keepAlive?.cancel();
_keepAlive = null;
_paused = false;
}
@override
Future<void> pause() async {
if (_utterance == null || _paused) return;
_paused = true;
_synth.pause();
}
@override
Future<void> stop() async {
_paused = false;
_keepAlive?.cancel();
_keepAlive = null;
_synth.cancel();
}
@override
Future<void> setRate(double rate) async => _rate = rate;
@override
Future<void> setVoice(SpeechVoice? voice) async {
_voice = voice == null
? null
: _browserVoices().where(
(item) => item.name == voice.name && item.lang == voice.locale,
).firstOrNull;
}
@override
Future<List<SpeechVoice>> voices() async {
var voices = _browserVoices();
// Browsers load their voice list asynchronously after the first request.
for (var attempt = 0; voices.isEmpty && attempt < 4; attempt++) {
await Future<void>.delayed(const Duration(milliseconds: 250));
voices = _browserVoices();
}
return [
for (final voice in voices)
SpeechVoice.fromPlatform({'name': voice.name, 'locale': voice.lang}),
];
}
List<web.SpeechSynthesisVoice> _browserVoices() =>
supported ? _synth.getVoices().toDart : const [];
}