import 'package:shared_preferences/shared_preferences.dart'; import 'speech_engine.dart'; const speechRateKey = 'pipelines.readAloud.rate.v1'; const speechVoiceNameKey = 'pipelines.readAloud.voiceName.v1'; const speechVoiceLocaleKey = 'pipelines.readAloud.voiceLocale.v1'; /// The normal speaking rate and the slider's bounds (a multiplier). const defaultSpeechRate = 1.0; const minSpeechRate = 0.5; const maxSpeechRate = 2.0; typedef SpeechPreferences = ({double rate, SpeechVoice? voice}); /// Device-local read-aloud settings. abstract interface class SpeechPreferencesStore { Future load(); Future save(SpeechPreferences preferences); } class SharedSpeechPreferencesStore implements SpeechPreferencesStore { const SharedSpeechPreferencesStore(); @override Future load() async { try { final prefs = await SharedPreferences.getInstance(); final name = prefs.getString(speechVoiceNameKey); final locale = prefs.getString(speechVoiceLocaleKey); return ( rate: prefs.getDouble(speechRateKey) ?? defaultSpeechRate, voice: name == null || locale == null ? null : SpeechVoice(name: name, locale: locale), ); } catch (_) { return null; } } @override Future save(SpeechPreferences preferences) async { try { final prefs = await SharedPreferences.getInstance(); final voice = preferences.voice; final saved = [ await prefs.setDouble(speechRateKey, preferences.rate), if (voice == null) ...[ await prefs.remove(speechVoiceNameKey), await prefs.remove(speechVoiceLocaleKey), ] else ...[ await prefs.setString(speechVoiceNameKey, voice.name), await prefs.setString(speechVoiceLocaleKey, voice.locale), ], ]; return !saved.contains(false); } catch (_) { return false; } } }