iOS 实现
你定义的接口需要在每个目标平台中实现。对于 iOS,这是通过 AVFoundation
框架完成的。ITextToSpeech
接口的以下实现处理用英语说出给定文本。
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);
}
}
创建类后,你需要启用 DependencyService
以在运行时发现它。这是通过在类定义之上添加 [assembly]
属性并在任何命名空间定义之外添加来完成的。
using AVFoundation;
using DependencyServiceSample.iOS;
[assembly: Xamarin.Forms.Dependency (typeof (TextToSpeechiOS))]
namespace DependencyServiceSample.iOS {
public class TextToSpeechiOS : ITextToSpeech
...
此属性使用 DependencyService
注册类,因此可在需要 ITextToSpeech
接口的实例时使用。