为此,您需要使用Dependency Service。
简而言之,在您的 PCL 中声明一个接口,该接口定义您想要使用的方法,例如:
public interface ITextToSpeech
{
void Speak (string text);
}
这可能是文本到语音实现的接口。现在在您的平台特定项目中实现该接口。对于 iOS,它可能如下所示:
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);
}
}
这是重要的部分:在命名空间上方用这个属性标记它。 [assembly: Xamarin.Forms.Dependency (typeof (TextToSpeechImplementation))]
您还需要将适当的 using 添加到您的项目中。
现在,在运行时,根据您所运行的平台,将为接口加载正确的实现。所以对于Android你做的完全一样,只是Speak方法的实现会有所不同。
在 PCL 中,您现在可以像这样访问它:DependencyService.Get<ITextToSpeech>().Speak("Hello from Xamarin Forms");
您可能应该检查DependencyService.Get<ITextToSpeech>() 方法是否不为空,这样您的应用程序就不会在您做错事时崩溃。但这应该涵盖基础知识。