import 'package:flutter/foundation.dart'; import 'package:flutter_tts/flutter_tts.dart'; class TtsService { static final TtsService _instance = TtsService._internal(); factory TtsService() => _instance; TtsService._internal(); final FlutterTts _flutterTts = FlutterTts(); bool _initialized = false; String? _selectedEngine; List _availableEngines = []; List get availableEngines => _availableEngines; String? get selectedEngine => _selectedEngine; Future init() async { if (_initialized) return; try { if (!kIsWeb) { // Query engines on Android try { final dynamic engines = await _flutterTts.getEngines; if (engines is List) { _availableEngines = engines.map((e) => e.toString()).toList(); debugPrint('Available TTS engines: $_availableEngines'); } } catch (e) { debugPrint('Error getting TTS engines: $e'); } try { final dynamic defaultEngine = await _flutterTts.getDefaultEngine; debugPrint('Default TTS engine: $defaultEngine'); if (defaultEngine != null && defaultEngine.toString().isNotEmpty) { _selectedEngine = defaultEngine.toString(); await _flutterTts.setEngine(_selectedEngine!); } else if (_availableEngines.isNotEmpty) { _selectedEngine = _availableEngines.first; await _flutterTts.setEngine(_selectedEngine!); } } catch (e) { debugPrint('Error setting TTS engine: $e'); } try { await _flutterTts.setIosAudioCategory( IosTextToSpeechAudioCategory.playback, [ IosTextToSpeechAudioCategoryOptions.duckOthers, IosTextToSpeechAudioCategoryOptions.defaultToSpeaker, ], ); } catch (_) {} } await _flutterTts.setLanguage("zh-CN"); await _flutterTts.setSpeechRate(0.5); // 适中语速 await _flutterTts.setVolume(1.0); // 满音量 await _flutterTts.setPitch(1.0); await _flutterTts.awaitSpeakCompletion(false); _initialized = true; debugPrint('TTS initialized successfully (engine: $_selectedEngine)'); } catch (e) { debugPrint('TTS init error: $e'); } } Future speak(String text) async { try { if (!_initialized) { await init(); } await _flutterTts.stop(); final dynamic result = await _flutterTts.speak(text); debugPrint('TTS speak "$text" -> $result'); return result == 1; } catch (e) { debugPrint('TTS speak error: $e'); return false; } } Future stop() async { try { await _flutterTts.stop(); } catch (_) {} } }