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 介面的例項時使用。