広告
Xamarin.Forms
- 「英語クイズ」を作るために「ITextToSpeech.csの新規作成」「_speechインスタンスの宣言」「iOSで音声再生」「Speechクラスのインスタンス」「再生ボタンの追加」を解説します。
- iOSでの音声再生を実装します。
プログラミング解説
- ITextToSpeech.csの新規作成
using System; namespace EnglishQuiz { public interface ITextToSpeech { void Speak (string text); } }
- IDEの左で「EnglishQuiz」フォルダを右クリックし「追加」→「新しいファイル」を実行します。
- 「General」→「空のクラス」で「名前」を「ITextToSpeech.cs」にして「新規」ボタンをクリックします。
- 「public interface ITextToSpeech」で「ITextToSpeech」インターフェースを定義します。
- 「void Speak (string text);」で引数に「string text」を持った「Speak」メソッドを定義します。
- _speechインスタンスの宣言
public partial class App : Application { public static ITextToSpeech _speech { get; set; } public static int _currentText { get; set; } public App() {
- 「EnglishQuiz.cs」ファイルを開きます。
- 「public static ITextToSpeech _speech { get; set; }」でITextToSpeechインターフェースのインスタンス「_speech」変数を宣言します。
- 「public static int _currentText { get; set; }」で英語問題の番号「_currentText」を宣言します。
- iOSで音声再生
using AVFoundation; namespace EnglishQuiz.iOS { public class Speech : ITextToSpeech { public void Speak (string text) { if (!string.IsNullOrWhiteSpace (text)) { var speechSynthesizer = new AVSpeechSynthesizer (); var speechUtterance = new AVSpeechUtterance (text) { Rate = AVSpeechUtterance.MaximumSpeechRate / 4, Voice = AVSpeechSynthesisVoice.FromLanguage ("en-US"), Volume = 1.0f, PitchMultiplier = 1.0f }; speechSynthesizer.SpeakUtterance (speechUtterance); } } } }
- 「EnglishQuiz.iOS」→「Speech.cs」ファイルを新規追加します。
- 上記のソースを「Speech.cs」ファイルにそのまま入力してください。
- ここではiOSで「text」変数を音声で喋る処理をしています。
- Speechクラスのインスタンス
public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); App._speech = new Speech(); LoadApplication(new App()); return base.FinishedLaunching(app, options); }
- 「AppDelegate.cs」ファイルを開きます。
- 「App._speech = new Speech();」で「App._speech」変数を「Speech();」クラスのインスタンスに宣言しています。
- 再生ボタンの追加
_englishListView.ItemsSource = _english; Random rnd = new Random(); App._currentText = rnd.Next(_english.Count); ToolbarItems.Add(new ToolbarItem { Text = "再生", Command = new Command(() => App._speech.Speak(_english[App._currentText].Text)) });
- 「EnglishQuizPage.xaml.cs」ファイルを開きます。
- 「Random rnd = new Random();」で乱数を宣言します。
- 「App._currentText = rnd.Next(_english.Count);」「App._currentText」変数に乱数「rnd.Next(_english.Count);」を代入します。
- 「ToolbarItems.Add(new ToolbarItem」でナビゲーションバーにツールバーアイテムを追加します。
- ツールバーアイテムの文字を「Text = "再生",」に設定します。
- 「Command = new Command(() => App._speech.Speak(_english
[App._currentText].Text))」で「再生」ボタンが押されたら問題の「Text」を音声再生します。 - IDE左上の▶ボタンで実行して、画面右上の再生ボタンを押したらいずれかの英単語の意味の文章が再生されましたね?