For this you will need to use the Dependency Service.
In short, in your PCL declare an interface which defines the methods that you would want to use, for example:
public interface ITextToSpeech
{
void Speak (string text);
}
This could be an interface for a text-to-speech implementation. Now in your platform-specific projects implement the interface. For iOS it could look like this:
using AVFoundation;
public class TextToSpeechImplementation : ITextToSpeech
{
public TextToSpeechImplementation () {}
public void Speak (string text)
{
var speechSynthesizer = new AVSpeechSynthesizer ();
var speechUtterance = new AVSpeechUtterance (text) {
Rate = AVSpeechUtterance.MaximumSpeechRate/4,
Voice = AVSpeechSynthesisVoice.FromLanguage ("en-US"),
Volume = 0.5f,
PitchMultiplier = 1.0f
};
speechSynthesizer.SpeakUtterance (speechUtterance);
}
}
Here is the important part: mark it with this attribute above the namespace. [assembly: Xamarin.Forms.Dependency (typeof (TextToSpeechImplementation))]
You will also need to add the appropriate using to your project.
Now, at runtime, depending on the platform you are running on the right implementation will be loaded for the interface. So for Android you do exactly the same, only the implementation of the Speak
method will be different.
In the PCL you can now access it like: DependencyService.Get<ITextToSpeech>().Speak("Hello from Xamarin Forms");
You should probably check if the DependencyService.Get<ITextToSpeech>()
method is not null so your app doesn't crash when you did something wrong. But this should cover the basics.