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 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 pause() async { if (_utterance == null || _paused) return; _paused = true; _synth.pause(); } @override Future stop() async { _paused = false; _keepAlive?.cancel(); _keepAlive = null; _synth.cancel(); } @override Future setRate(double rate) async => _rate = rate; @override Future setVoice(SpeechVoice? voice) async { _voice = voice == null ? null : _browserVoices().where( (item) => item.name == voice.name && item.lang == voice.locale, ).firstOrNull; } @override Future> 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.delayed(const Duration(milliseconds: 250)); voices = _browserVoices(); } return [ for (final voice in voices) SpeechVoice.fromPlatform({'name': voice.name, 'locale': voice.lang}), ]; } List _browserVoices() => supported ? _synth.getVoices().toDart : const []; }