【Android開発】SpeechRecognizer APIで音声認識を実装する方法をステップ解説
この記事では、Androidアプリに音声認識機能を実装できる「SpeechRecognizer API」の基本的な使い方を、実際に動作するサンプルコードとともにステップ形式で解説します。
サンプルアプリでは、起動と同時に音声認識が開始され、「地球上で最大のオンライン小売企業はどこ?」という質問への回答をマイク経由で受け付けます。認識した回答に「AMAZON」が含まれていれば正解、含まれていなければ不正解として、判定結果をTextViewに表示します。
手順1:Android Studioで新規プロジェクトを作成する
まずはAndroid Studioで新しいプロジェクトを作成しましょう。メニューから「File → New Project」を選択し、必要事項をすべて入力してプロジェクトを作成します。
手順2:レイアウトファイル(activity_main.xml)を編集する
res/layout/activity_main.xml に以下のコードを追加します。認識結果と判定メッセージを表示するためのTextViewを1つ配置しています。
<?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:padding="16sp"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
手順3:MainActivity.java を編集する
src/MainActivity.java に以下のコードを追加します。
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private final int REQUEST_SPEECH_RECOGNIZER = 3000;
private TextView textView;
private final String mQuestion = "Which company is the largest online retailer on the planet?";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
startSpeechRecognizer();
}
private void startSpeechRecognizer() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, mQuestion);
startActivityForResult(intent, REQUEST_SPEECH_RECOGNIZER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_SPEECH_RECOGNIZER) {
if (resultCode == RESULT_OK) {
List<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String mAnswer = results.get(0);
if (mAnswer.toUpperCase().contains("AMAZON"))
textView.setText(String.format("\n\nQuestion: %s\n\nYour answer is '%s' and it is
correct!", mQuestion, mAnswer));
else
textView.setText(String.format("\n\nQuestion: %s\n\nYour answer is '%s' and it is
incorrect!", mQuestion, mAnswer));
}
}
}
}
コードのポイント
- RecognizerIntent.ACTION_RECOGNIZE_SPEECH:システム標準の音声認識ダイアログを呼び出すためのインテントアクションです。
- EXTRA_LANGUAGE_MODEL:「LANGUAGE_MODEL_FREE_FORM」を指定すると、自由形式の発話を認識できます。
- EXTRA_PROMPT:音声入力画面に表示される案内文(ここでは質問文)を設定します。
- onActivityResult():認識結果は文字列リスト(EXTRA_RESULTS)として返され、先頭の要素が最も信頼度の高い結果になります。
補足:startActivityForResult() と onActivityResult() は現在非推奨のAPIです。最新のAndroidX環境では、ActivityResultContracts.StartActivityForResult を利用した実装が推奨されているため、新規プロジェクトでは新しいAPIの採用を検討してください。
手順4:AndroidManifest.xml に権限を追加する
マイクで録音を行うため、androidManifest.xml に RECORD_AUDIO パーミッションを追加します。
<?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>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
</manifest>
アプリを実行してみる
それでは、作成したアプリを実行してみましょう。ここでは、実機のAndroidスマートフォンをPCに接続している前提で説明を進めます。Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーのRun
アイコンをクリックしてください。実行デバイスとして接続したスマートフォンを選択すると、端末側にアプリの初期画面が表示されます。


音声認識のダイアログが表示されたら、マイクに向かって「Amazon」と話しかけてみてください。認識結果に応じて正誤判定が画面に表示されれば、実装は成功です。
-
【Android】CheckBox(チェックボックス)の使い方をサンプルコード付きで解説
はじめにこの記事では、AndroidアプリでCheckBox(チェックボックス)を使用する方法を、実際のコード例とともにわかりやすく解説します。CheckBoxは、ユーザーに複数の項目を選ばせたい場合に便利なUI部品です。RadioButtonがグループ内で1つしか選択できないのに対し、CheckBoxは複数選択が可能という点が大きな特徴です。このチュートリアルでは、「ピザ」「コーヒー」「バーガー」の3つの商品を選択し、ボタンを押すと選択された商品と合計金額をToastで表示する、シンプルな注文アプリを作成します。手順1:Android Studioで新規プロジェクトを作成するAndroid
-
【Android】NavigationViewの実装方法をステップごとに解説
この記事では、AndroidアプリでNavigationView(ナビゲーションビュー)を使用してドロワーメニューを実装する方法を、ステップごとに詳しく解説します。ハンバーガーアイコンから開閉できるサイドメニューは、多くのアプリで採用されている定番のUIです。ステップ1:新しいプロジェクトを作成するAndroid Studioを開き、File → New Project を選択して、必要な情報を入力し新しいプロジェクトを作成します。テンプレートには「Navigation Drawer Activity」を選ぶと、後の作業がスムーズになります。ステップ2:activity_main.xml にコ