Androidで音声再生
using System;
using System.Collections.Generic;
using Android.Speech.Tts;
using Xamarin.Forms;
using Android.OS;
namespace EnglishQuiz.Droid
{
public class Speech : Java.Lang.Object, ITextToSpeech, TextToSpeech.IOnInitListener
{
TextToSpeech _textToSpeech;
string _toSpeak;
public void Speak (string text)
{
if (!string.IsNullOrWhiteSpace (text)) {
_toSpeak = text;
if (_textToSpeech == null) {
_textToSpeech = new TextToSpeech (Forms.Context, this);
} else {
OnSpeak(_toSpeak);
}
}
}
public void OnInit (OperationResult status)
{
if (status.Equals (OperationResult.Success)) {
OnSpeak(_toSpeak);
}
}
private void OnSpeak(string text)
{
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
{
_textToSpeech.Speak(text, QueueMode.Flush, null, null);
}
else
{
_textToSpeech.Speak(text, QueueMode.Flush, null);
}
}
}
}
- IDE左の「EnglishQuiz.Droid」を右クリックメニューで「スタートアッププロジェクトとして設定」を実行します。
- IDE左の「EnglishQuiz.Droid」を右クリックメニューで「追加」→「新しいファイル」を実行します。
- 「General」→「空のクラス」を選択し、「名前」に「Speech.cs」と入力して、「新規」ボタンをクリックします。
- 「Speech.cs」ファイルに上記を入力します。
- このクラスではAndroidで音声を再生するクラスを実装しています。