import 'dart:async'; import 'package:flutter/material.dart'; import '../chat/speech/speech.dart'; bool needsSpeechVoiceHint( List voices, String language, { bool supportsVoiceDownloadHint = false, }) { if (!supportsVoiceDownloadHint) return false; return voices .where((voice) => voice.language == language.toLowerCase()) .every((voice) => !voice.isNatural); } /// The picker's answer: a voice, or null for the system default. typedef SpeechVoiceChoice = ({SpeechVoice? voice}); /// Lists the platform's voices grouped by language, the device's language /// first, each with a sample. Resolves to null when dismissed. Future showSpeechVoicePicker( BuildContext context, SpeechController speech, ) async { final choice = await showDialog( context: context, builder: (_) => _VoicePickerDialog(speech: speech), ); if (speech.messageId == speechSampleId) unawaited(speech.stop()); return choice; } /// Voices grouped by language subtag, the [device] language first and the /// rest by name; natural voices and offline voices come first within a group. List<({String language, List voices})> groupSpeechVoices( List voices, String device, ) { final groups = >{}; for (final voice in voices) { (groups[voice.language] ??= []).add(voice); } final languages = groups.keys.toList() ..sort((a, b) { if (a == device.toLowerCase()) return -1; if (b == device.toLowerCase()) return 1; return speechLanguageName(a).compareTo(speechLanguageName(b)); }); return [ for (final language in languages) ( language: language, voices: groups[language]!..sort(compareSpeechVoices), ), ]; } /// An English name for common language subtags; others show their code. String speechLanguageName(String language) => _languageNames[language] ?? language.toUpperCase(); const _languageNames = { 'ar': 'Arabic', 'bg': 'Bulgarian', 'ca': 'Catalan', 'cs': 'Czech', 'da': 'Danish', 'de': 'German', 'el': 'Greek', 'en': 'English', 'es': 'Spanish', 'fi': 'Finnish', 'fr': 'French', 'he': 'Hebrew', 'hi': 'Hindi', 'hr': 'Croatian', 'hu': 'Hungarian', 'id': 'Indonesian', 'it': 'Italian', 'ja': 'Japanese', 'ko': 'Korean', 'ms': 'Malay', 'nb': 'Norwegian', 'nl': 'Dutch', 'pl': 'Polish', 'pt': 'Portuguese', 'ro': 'Romanian', 'ru': 'Russian', 'sk': 'Slovak', 'sv': 'Swedish', 'th': 'Thai', 'tr': 'Turkish', 'uk': 'Ukrainian', 'vi': 'Vietnamese', 'zh': 'Chinese', }; class _VoicePickerDialog extends StatefulWidget { const _VoicePickerDialog({required this.speech}); final SpeechController speech; @override State<_VoicePickerDialog> createState() => _VoicePickerDialogState(); } class _VoicePickerDialogState extends State<_VoicePickerDialog> { late final Future> _voices = widget.speech.voices(); String _keyOf(SpeechVoice? voice) => voice == null ? '' : '${voice.name}\n${voice.locale}'; @override Widget build(BuildContext context) { final device = View.of(context).platformDispatcher.locale.languageCode; return AlertDialog( title: const Text('Voice'), contentPadding: const EdgeInsets.symmetric(vertical: 16), // A list needs a definite width; keep it to a readable dialog measure. content: ConstrainedBox( constraints: BoxConstraints( maxWidth: 560, maxHeight: MediaQuery.sizeOf(context).height * .6, ), child: SizedBox( width: double.maxFinite, child: FutureBuilder>( future: _voices, builder: (context, snapshot) { if (snapshot.connectionState != ConnectionState.done) { return const Center(child: CircularProgressIndicator()); } if (snapshot.hasError) { return Padding( padding: const EdgeInsets.all(24), child: Text( 'Voices could not be loaded. You can cancel and try again.', style: TextStyle( color: Theme.of(context).colorScheme.onSurfaceVariant, ), ), ); } final voices = snapshot.data ?? const []; return _list(context, groupSpeechVoices(voices, device)); }, ), ), ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('Cancel'), ), ], ); } Widget _list( BuildContext context, List<({String language, List voices})> groups, ) { final theme = Theme.of(context); final header = theme.textTheme.titleSmall?.copyWith( color: theme.colorScheme.primary, ); return RadioGroup( groupValue: _keyOf(widget.speech.voice), onChanged: (key) { final voice = [ for (final group in groups) ...group.voices, ].where((voice) => _keyOf(voice) == key).firstOrNull; Navigator.of(context).pop((voice: voice)); }, child: ListView( primary: false, children: [ const RadioListTile( value: '', title: Text('Automatic (most natural)'), ), if (groups.isEmpty) Padding( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8), child: Text( 'This device offers no other voices.', style: TextStyle(color: theme.colorScheme.onSurfaceVariant), ), ), for (final group in groups) ...[ Padding( padding: const EdgeInsetsDirectional.fromSTEB(24, 16, 24, 4), child: Semantics( header: true, child: Text(speechLanguageName(group.language), style: header), ), ), for (final voice in group.voices) // The sample is its own control beside the choice, not merged // into the radio tile's semantics. Row( children: [ Expanded( child: RadioListTile( value: _keyOf(voice), title: Row( children: [ Flexible(child: Text(voice.name)), if (voice.isNatural) Padding( padding: const EdgeInsetsDirectional.only( start: 8, ), child: Text( 'Natural', style: theme.textTheme.labelSmall?.copyWith( color: theme.colorScheme.primary, ), ), ), ], ), subtitle: Text(voice.locale), ), ), Padding( padding: const EdgeInsetsDirectional.only(end: 12), child: IconButton( tooltip: 'Play sample of ${voice.name}', onPressed: () => unawaited(widget.speech.sample(voice)), icon: const Icon(Icons.play_arrow_outlined), ), ), ], ), ], ], ), ); } }