1+ using System . Globalization ;
2+ using CommunityToolkit . Maui . Alerts ;
3+ using CommunityToolkit . Maui . SpeechToText ;
4+ using CommunityToolkit . Mvvm . ComponentModel ;
5+ using CommunityToolkit . Mvvm . Input ;
6+
7+ namespace CommunityToolkit . Maui . Sample . ViewModels . Essentials ;
8+
9+ public partial class SpeechToTextViewModel : BaseViewModel
10+ {
11+ readonly ITextToSpeech textToSpeech ;
12+ readonly ISpeechToText speechToText ;
13+ [ ObservableProperty ]
14+ List < Locale > ? locales ;
15+
16+ [ ObservableProperty ]
17+ Locale ? locale ;
18+
19+ [ ObservableProperty ]
20+ string text ;
21+
22+ [ ObservableProperty ]
23+ string ? recognitionText ;
24+
25+ public SpeechToTextViewModel ( ITextToSpeech textToSpeech , ISpeechToText speechToText )
26+ {
27+ this . textToSpeech = textToSpeech ;
28+ this . speechToText = speechToText ;
29+ Locales = new ( ) ;
30+ text = @"Welcome to .NET MAUI Community Toolkit!" ;
31+ SetLocalesCommand . Execute ( null ) ;
32+ }
33+
34+ [ RelayCommand ]
35+ async Task SetLocales ( )
36+ {
37+ Locales = ( await textToSpeech . GetLocalesAsync ( ) ) . ToList ( ) ;
38+ Locale = Locales . FirstOrDefault ( ) ;
39+ }
40+
41+ [ RelayCommand ]
42+ async Task Play ( CancellationToken cancellationToken )
43+ {
44+ await textToSpeech . SpeakAsync ( Text , new SpeechOptions ( )
45+ {
46+ Locale = Locale ,
47+ Pitch = 2 ,
48+ Volume = 1
49+ } , cancellationToken ) ;
50+ }
51+
52+ [ RelayCommand ( IncludeCancelCommand = true ) ]
53+ async Task Listen ( CancellationToken cancellationToken )
54+ {
55+ try
56+ {
57+ RecognitionText = await speechToText . Listen ( CultureInfo . GetCultureInfo ( Locale ? . Language ?? "en-us" ) , new Progress < string > ( partialText =>
58+ {
59+ RecognitionText += partialText + " " ;
60+ } ) , cancellationToken ) ;
61+ }
62+ catch ( Exception ex )
63+ {
64+ await Toast . Make ( ex . Message ) . Show ( CancellationToken . None ) ;
65+ }
66+ }
67+ }
0 commit comments