The interface you defined needs to be implemented in every targeted platform. For iOS this is done through the AVFoundation
framework. The following implementation of the ITextToSpeech
interface handles speaking a given text in English.
using AVFoundation;
public class TextToSpeechiOS : ITextToSpeech
{
public TextToSpeechiOS () {}
public void Speak (string whatToSay)
{
var speechSynthesizer = new AVSpeechSynthesizer ();
var speechUtterance = new AVSpeechUtterance (whatToSay) {
Rate = AVSpeechUtterance.MaximumSpeechRate/4,
Voice = AVSpeechSynthesisVoice.FromLanguage ("en-US"),
Volume = 0.5f,
PitchMultiplier = 1.0f
};
speechSynthesizer.SpeakUtterance (speechUtterance);
}
}
When you've created your class you need to enable the DependencyService
to discover it at run time. This is done by adding an [assembly]
attribute above the class definition and outside of any namespace definitions.
using AVFoundation;
using DependencyServiceSample.iOS;
[assembly: Xamarin.Forms.Dependency (typeof (TextToSpeechiOS))]
namespace DependencyServiceSample.iOS {
public class TextToSpeechiOS : ITextToSpeech
...
This attribute registers the class with the DependencyService
so it can be used when an instance of the ITextToSpeech
interface is needed.