1
- using System . Collections . Generic ;
1
+ using System ;
2
+ using System . Collections . Generic ;
2
3
using System . Linq ;
3
4
using System . Threading ;
4
5
using System . Threading . Tasks ;
@@ -8,14 +9,18 @@ namespace Xamarin.Essentials
8
9
{
9
10
public static partial class TextToSpeech
10
11
{
12
+ static readonly Lazy < AVSpeechSynthesizer > speechSynthesizer = new Lazy < AVSpeechSynthesizer > ( ) ;
13
+
11
14
internal static Task < IEnumerable < Locale > > PlatformGetLocalesAsync ( ) =>
12
15
Task . FromResult ( AVSpeechSynthesisVoice . GetSpeechVoices ( )
13
16
. Select ( v => new Locale ( v . Language , null , v . Language , v . Identifier ) ) ) ;
14
17
15
- internal static Task PlatformSpeakAsync ( string text , SpeechOptions options , CancellationToken cancelToken = default )
18
+ internal static async Task PlatformSpeakAsync ( string text , SpeechOptions options , CancellationToken cancelToken = default )
16
19
{
17
- var speechUtterance = GetSpeechUtterance ( text , options ) ;
18
- return SpeakUtterance ( speechUtterance , cancelToken ) ;
20
+ using ( var speechUtterance = GetSpeechUtterance ( text , options ) )
21
+ {
22
+ await SpeakUtterance ( speechUtterance , cancelToken ) ;
23
+ }
19
24
}
20
25
21
26
static AVSpeechUtterance GetSpeechUtterance ( string text , SpeechOptions options )
@@ -44,24 +49,23 @@ static AVSpeechUtterance GetSpeechUtterance(string text, SpeechOptions options)
44
49
internal static async Task SpeakUtterance ( AVSpeechUtterance speechUtterance , CancellationToken cancelToken )
45
50
{
46
51
var tcsUtterance = new TaskCompletionSource < bool > ( ) ;
47
- var speechSynthesizer = new AVSpeechSynthesizer ( ) ;
48
52
try
49
53
{
50
- speechSynthesizer . DidFinishSpeechUtterance += OnFinishedSpeechUtterance ;
51
- speechSynthesizer . SpeakUtterance ( speechUtterance ) ;
54
+ speechSynthesizer . Value . DidFinishSpeechUtterance += OnFinishedSpeechUtterance ;
55
+ speechSynthesizer . Value . SpeakUtterance ( speechUtterance ) ;
52
56
using ( cancelToken . Register ( TryCancel ) )
53
57
{
54
58
await tcsUtterance . Task ;
55
59
}
56
60
}
57
61
finally
58
62
{
59
- speechSynthesizer . DidFinishSpeechUtterance -= OnFinishedSpeechUtterance ;
63
+ speechSynthesizer . Value . DidFinishSpeechUtterance -= OnFinishedSpeechUtterance ;
60
64
}
61
65
62
66
void TryCancel ( )
63
67
{
64
- speechSynthesizer ? . StopSpeaking ( AVSpeechBoundary . Word ) ;
68
+ speechSynthesizer . Value ? . StopSpeaking ( AVSpeechBoundary . Word ) ;
65
69
tcsUtterance ? . TrySetResult ( true ) ;
66
70
}
67
71
0 commit comments