Android
 Computer >> コンピューター >  >> プログラミング >> Android

AndroidアプリでTextToSpeech(音声読み上げ)機能を実装する方法をわかりやすく解説

このチュートリアルでは、AndroidアプリにTextToSpeech(音声合成・TTS)機能を実装し、入力したテキストを音声で読み上げる方法を解説します。サンプルでは、シークバーを使って音声のピッチ(声の高さ)スピード(話す速さ)を調整できる、実用的な構成になっています。

手順1:Android Studioで新規プロジェクトを作成

Android Studioを起動し、メニューから File ⇒ New Project を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。

手順2:レイアウトファイル(activity_main.xml)を編集

res/layout/activity_main.xml に以下のコードを追加します。画面には、テキスト入力用のEditText、ピッチとスピードを調整する2つのSeekBar、読み上げを実行するButtonが縦一列に並びます。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
   xmlns:tools="https://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/editText"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_marginBottom="16dp"
      android:hint="Enter Text" />
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Pitch"
      android:textSize="16sp" />
   <SeekBar
      android:id="@+id/seekBarPitch"
      android:layout_width="200dp"
      android:layout_height="wrap_content"
      android:progress="50" />
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Speed"
      android:textSize="16sp" />
   <SeekBar
      android:id="@+id/seekBarSpeed"
      android:layout_width="200dp"
      android:layout_height="wrap_content"
      android:layout_marginBottom="16dp"
      android:progress="50" />
   <Button
      android:id="@+id/btnSpeak"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center_horizontal"
      android:enabled="false"
      android:text="Say it!" />
</LinearLayout>

手順3:MainActivity.java を実装

src/MainActivity.java に以下のコードを追加します。

import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
   private TextToSpeech textToSpeech;
   private EditText editText;
   private SeekBar seekBarPitch;
   private SeekBar seekBarSpeed;
   private Button buttonSpeak;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      buttonSpeak = findViewById(R.id.btnSpeak);
      textToSpeech = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
         @Override
         public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
               int result = textToSpeech.setLanguage(Locale.ENGLISH);
               if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                  Log.e("TextToSpeech", "Language not supported");
               } else {
                  buttonSpeak.setEnabled(true);
               }
            } else {
               Log.e("TextToSpeech", "Initialization failed");
            }
         }
      });
      editText = findViewById(R.id.editText);
      seekBarPitch = findViewById(R.id.seekBarPitch);
      seekBarSpeed = findViewById(R.id.seekBarSpeed);
      buttonSpeak.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            speak();
         }
      });
   }
   private void speak() {
      String text = editText.getText().toString();
      float pitch = (float) seekBarPitch.getProgress() / 50;
      if (pitch < 0.1) pitch = 0.1f;
      float speed = (float) seekBarSpeed.getProgress() / 50;
      if (speed < 0.1) speed = 0.1f;
      textToSpeech.setPitch(pitch);
      textToSpeech.setSpeechRate(speed);
      textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
   }
   @Override
   protected void onDestroy() {
      if (textToSpeech != null) {
         textToSpeech.stop();
         textToSpeech.shutdown();
      }
      super.onDestroy();
   }
}

コードのポイント

  • TextToSpeechの初期化結果は、OnInitListenerの onInit() で受け取ります。成功した場合は setLanguage(Locale.ENGLISH) で英語を設定します。
  • LANG_MISSING_DATA や LANG_NOT_SUPPORTED が返された場合は、言語データの不足または未対応を意味するため、ログに出力してボタンを無効のままにします。
  • speak() メソッドでは、シークバーの値を50で割ってピッチとスピードを算出します(0.5〜2.0程度の範囲になり、最小値は0.1に制限)。setPitch() と setSpeechRate() で設定してから speak() を呼び出すことで、読み上げが開始されます。
  • QUEUE_FLUSH を指定すると、現在読み上げ中の音声を停止して新しいテキストを即座に再生できます。
  • onDestroy() 内で stop() と shutdown() を必ず呼び出し、TTSエンジンのリソースを解放しましょう。これを怠るとメモリリークの原因になります。
  • なお、新しいプロジェクトではサポートライブラリの代わりに androidx.appcompat.app.AppCompatActivity を使用してください。

手順4:AndroidManifest.xml を確認

androidManifest.xml に以下のコードを追加します。TextToSpeechはシステムの音声エンジンを利用するため、特別なパーミッションの宣言は不要です。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

アプリを実行してみよう

それでは、作成したアプリを実行してみましょう。ここでは、実際のAndroid端末をパソコンに接続しているものとして説明します。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの Run アイコンをクリックしてください。表示された候補から接続中のモバイルデバイスを選択すると、端末に以下のような画面が表示されます。

AndroidアプリでTextToSpeech(音声読み上げ)機能を実装する方法をわかりやすく解説

  1. 【Android】XMLファイルを使ってアニメーションを作成する方法をわかりやすく解説

    この記事では、AndroidアプリにおいてXMLファイルを使用してアニメーションを作成する方法を、実際のコード例とともに段階的に解説します。View Animation(Tween Animation)は、res/animディレクトリに配置したリソースファイルとして定義できるため、フェードインやズーム、点滅といった演出をJava側のコードをほとんど書かずに実現できるのが特徴です。 ステップ1:新規プロジェクトの作成 Android Studioを起動し、メニューから「File」⇒「New Project」を選択して新しいプロジェクトを作成します。ウィザードに従って必要な情報を入力し、プロジェク

  2. Androidのホーム画面にショートカットを作成する方法【サイト・ブックマーク・ファイル対応】

    スマホにすでにインストール済みのアプリをホーム画面に追加する方法は、多くの方がご存じでしょう。アプリドロワー(アプリ一覧)を開き、アプリアイコンを長押ししてつかみ、好きなホーム画面までドラッグするだけです。しかし、特定のフォルダやWebページ、ブックマーク一覧などへの「アプリのようなショートカット」を作りたいと思ったことはありませんか?その場合は、もう少し踏み込んだ操作が必要になります。この記事では、Androidであらゆるものへのホーム画面ショートカットを作成する方法をわかりやすくご紹介します。Webサイトへのショートカットを作成するWebサイトへのショートカット作成はとても簡単です。Chr