Skip to content
This repository was archived by the owner on May 15, 2024. It is now read-only.

Commit a610b50

Browse files
authored
Merge pull request #1153 from baskren/gh-1112
Fix to fatal iOS 13 memory leak when using TextToSpeach.SpeekAsync #1112
2 parents e9d62fc + 852e563 commit a610b50

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

Xamarin.Essentials/TextToSpeech/TextToSpeech.ios.tvos.watchos.cs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using System.Collections.Generic;
1+
using System;
2+
using System.Collections.Generic;
23
using System.Linq;
34
using System.Threading;
45
using System.Threading.Tasks;
@@ -8,14 +9,18 @@ namespace Xamarin.Essentials
89
{
910
public static partial class TextToSpeech
1011
{
12+
static readonly Lazy<AVSpeechSynthesizer> speechSynthesizer = new Lazy<AVSpeechSynthesizer>();
13+
1114
internal static Task<IEnumerable<Locale>> PlatformGetLocalesAsync() =>
1215
Task.FromResult(AVSpeechSynthesisVoice.GetSpeechVoices()
1316
.Select(v => new Locale(v.Language, null, v.Language, v.Identifier)));
1417

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)
1619
{
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+
}
1924
}
2025

2126
static AVSpeechUtterance GetSpeechUtterance(string text, SpeechOptions options)
@@ -44,24 +49,23 @@ static AVSpeechUtterance GetSpeechUtterance(string text, SpeechOptions options)
4449
internal static async Task SpeakUtterance(AVSpeechUtterance speechUtterance, CancellationToken cancelToken)
4550
{
4651
var tcsUtterance = new TaskCompletionSource<bool>();
47-
var speechSynthesizer = new AVSpeechSynthesizer();
4852
try
4953
{
50-
speechSynthesizer.DidFinishSpeechUtterance += OnFinishedSpeechUtterance;
51-
speechSynthesizer.SpeakUtterance(speechUtterance);
54+
speechSynthesizer.Value.DidFinishSpeechUtterance += OnFinishedSpeechUtterance;
55+
speechSynthesizer.Value.SpeakUtterance(speechUtterance);
5256
using (cancelToken.Register(TryCancel))
5357
{
5458
await tcsUtterance.Task;
5559
}
5660
}
5761
finally
5862
{
59-
speechSynthesizer.DidFinishSpeechUtterance -= OnFinishedSpeechUtterance;
63+
speechSynthesizer.Value.DidFinishSpeechUtterance -= OnFinishedSpeechUtterance;
6064
}
6165

6266
void TryCancel()
6367
{
64-
speechSynthesizer?.StopSpeaking(AVSpeechBoundary.Word);
68+
speechSynthesizer.Value?.StopSpeaking(AVSpeechBoundary.Word);
6569
tcsUtterance?.TrySetResult(true);
6670
}
6771

0 commit comments

Comments
 (0)