Skip to content

Instantly share code, notes, and snippets.

@praeclarum
Created June 26, 2014 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save praeclarum/e15b3271c32898f0a57d to your computer and use it in GitHub Desktop.
Save praeclarum/e15b3271c32898f0a57d to your computer and use it in GitHub Desktop.
Easy way to asynchronously speak some text on iOS with C#
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