Thursday, 26 September 2013

iOS SpeechSynthesizer API with Xamarin: it talks!

Mike posted a neat code example today on adding the new iOS 7 AVSpeechSynthensizer API to a Xamarin app.

It's so easy, I added speech synthesis to the this TaskBoard to-do list example in about 5 lines of code. Now the app can read the to-do item back to you :) just by adding this code:

if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) {
   SpeakButton.TouchUpInside += (sender, e) => {    // requires iOS 7
      Speak (TitleText.Text + ". " + NotesText.Text);
   };
}

and

void Speak (string text) {
   var speechSynthesizer = new AVSpeechSynthesizer ();

   var speechUtterance = new AVSpeechUtterance (text) {
      Rate = AVSpeechUtterance.MaximumSpeechRate/4,
      Voice = AVSpeechSynthesisVoice.FromLanguage ("en-AU"),
      Volume = 0.5f,
      PitchMultiplier = 1.0f
   };

   speechSynthesizer.SpeakUtterance (speechUtterance);
}

The UI now looks like this: touch the Speak button to hear the text read back to you.

No comments:

Post a Comment