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, }; @override bool get supportsVoiceDownloadHint => !kIsWeb && (defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.macOS); /// 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 speak(String text) async => _tts.speak(text); @override Future pause() async => _tts.pause(); @override Future stop() async => _tts.stop(); @override Future setRate(double rate) async => _tts.setSpeechRate(platformSpeechRate(rate, appleScale: _appleScale)); @override Future 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> 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.delayed(const Duration(milliseconds: 250)); voices = await _readVoices(); } return voices; } Future> _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.fromPlatform(item.cast()), ]; } } /// The app's 1.0× reads at a calm listening pace, a little under the /// platform's own normal rate, which sounds rushed for long replies. const readAloudPace = 0.8; /// The platform rate for the app's [rate] multiplier (1.0× = [readAloudPace] /// of the platform's normal): AVSpeechSynthesizer's normal is 0.5 on a 0..1 /// scale, Android's TextToSpeech and the Web Speech API use 1.0. double platformSpeechRate(double rate, {required bool appleScale}) { final paced = rate * readAloudPace; return appleScale ? (paced * 0.5).clamp(0, 1) : paced; }