Created
June 26, 2014 19:08
-
-
Save praeclarum/e15b3271c32898f0a57d to your computer and use it in GitHub Desktop.
Easy way to asynchronously speak some text on iOS with C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using MonoTouch.AVFoundation; | |
using System.Collections.Generic; | |
using System.Threading.Tasks; | |
namespace Praeclarum | |
{ | |
/// <summary> | |
/// Easy way to asynchronously speak some text. | |
/// <code> | |
/// await Speaker.SayAsync ("Hello"); | |
/// await Speaker.SayAsync ("World"); | |
/// </code> | |
/// </summary> | |
public static class Speaker | |
{ | |
static AVSpeechSynthesizer synth = null; | |
// static AVSpeechSynthesisVoice synthVoice = null; | |
static readonly Dictionary<AVSpeechUtterance, UtteranceInfo> activeUtterances = new Dictionary<AVSpeechUtterance, UtteranceInfo> (); | |
/// <summary> | |
/// Speaks the text passed in. | |
/// </summary> | |
/// <returns>The speach task.</returns> | |
/// <param name="text">The text to speak.</param> | |
public static Task SayAsync (string text) | |
{ | |
if (synth == null) { | |
synth = new AVSpeechSynthesizer (); | |
synth.DidFinishSpeechUtterance += HandleDidFinishSpeechUtterance; | |
} | |
// if (synthVoice == null) { | |
// foreach (var v in AVSpeechSynthesisVoice.GetSpeechVoices ()) { | |
// Console.WriteLine (v.Language); | |
// } | |
// synthVoice = AVSpeechSynthesisVoice.FromLanguage ("en-GB"); | |
// } | |
var utt = new UtteranceInfo (text); | |
activeUtterances [utt.Utterance] = utt; | |
synth.SpeakUtterance (utt.Utterance); | |
return utt.Completion.Task; | |
} | |
class UtteranceInfo | |
{ | |
public readonly AVSpeechUtterance Utterance; | |
public readonly TaskCompletionSource<object> Completion; | |
public UtteranceInfo (string text) | |
{ | |
Utterance = new AVSpeechUtterance (text) { | |
Rate = 0.333f, | |
// PitchMultiplier = 0.9f, | |
}; | |
Completion = new TaskCompletionSource<object> (); | |
} | |
} | |
static void HandleDidFinishSpeechUtterance (object sender, AVSpeechSynthesizerUteranceEventArgs e) | |
{ | |
UtteranceInfo info; | |
if (activeUtterances.TryGetValue (e.Utterance, out info)) { | |
activeUtterances.Remove (e.Utterance); | |
info.Completion.SetResult (null); | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment