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

Androidで音声をテキストに変換する方法|RecognizerIntentによる音声認識の実装手順

Androidには、Googleが内蔵する音声認識APIが標準で用意されており、RecognizerIntent.ACTION_RECOGNIZE_SPEECHを利用することで、音声入力をテキストへ変換する機能を簡単に組み込めます。本記事では、Androidアプリに「音声→テキスト」変換機能を統合する具体的な手順を、サンプルコードとともに段階的に解説します。

ステップ1:新規プロジェクトを作成する

Android Studioを起動し、「File」→「New Project」を選択します。必要事項をすべて入力して、新しいプロジェクトを作成してください。

ステップ2:レイアウトファイル(activity_main.xml)を作成する

res/layout/activity_main.xml に以下のコードを記述します。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:gravity="center"
        android:layout_height="match_parent">
        <TextView
            android:id="@+id/text"
            android:textSize="30sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:orientation="vertical"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="?selectableItemBackground"
            android:src="@android:drawable/ic_btn_speak_now"/>
    </LinearLayout>
</RelativeLayout>

このレイアウトでは、画面中央に認識結果を表示するためのTextViewを1つ、画面下部にマイクアイコンのImageViewを配置しています。ユーザーがImageViewをタップすると、Googleの音声認識APIが呼び出され、認識されたテキストがTextViewに反映される仕組みです。

ステップ3:MainActivity.java を実装する

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

package com.example.andy.myapplication;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.speech.RecognizerIntent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {
    private final int REQ_CODE = 100;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);
        ImageView speak = findViewById(R.id.speak);
        speak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                        RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
                intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "話しかけてください");
                try {
                    startActivityForResult(intent, REQ_CODE);
                } catch (ActivityNotFoundException a) {
                    Toast.makeText(getApplicationContext(),
                            "申し訳ありませんが、お使いの端末は音声認識に対応していません",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQ_CODE: {
                if (resultCode == RESULT_OK && data != null) {
                    ArrayList<String> result = data
                            .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                    textView.setText(result.get(0));
                }
                break;
            }
        }
    }
}

音声認識インテントの呼び出し部分のポイント

ユーザーがImageView(マイクボタン)をタップすると、以下のインテントが発行され、音声入力ダイアログが起動します。

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "話しかけてください");
try {
    startActivityForResult(intent, REQ_CODE);
} catch (ActivityNotFoundException a) {
    Toast.makeText(getApplicationContext(), "申し訳ありませんが、お使いの端末は音声認識に対応していません", Toast.LENGTH_SHORT).show();
}
  • ACTION_RECOGNIZE_SPEECH: 音声認識アクティビティを起動するためのインテントアクションです。
  • EXTRA_LANGUAGE_MODEL: 自由形式の音声認識(LANGUAGE_MODEL_FREE_FORM)を指定しています。
  • EXTRA_LANGUAGE: 端末のデフォルトロケール(言語設定)に基づいて認識を行います。
  • EXTRA_PROMPT: 音声入力ダイアログに表示される案内メッセージです。

端末に音声認識アプリがインストールされていないケースに備えて、ActivityNotFoundExceptionをキャッチし、トーストで通知している点もポイントです。

認識結果を受け取る(onActivityResult)

音声認識の結果は、onActivityResult() で受け取ります。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case REQ_CODE: {
            if (resultCode == RESULT_OK && data != null) {
                ArrayList<String> result = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                textView.setText(result.get(0));
            }
            break;
        }
    }
}

認識結果はArrayList(候補のリスト)として返されるため、ここでは最も可能性の高い先頭(0番目)の要素を取り出し、TextViewに表示しています。

アプリを実行してみよう

それでは、実際にアプリを動かしてみましょう。Android端末をPCに接続したうえで、Android Studioでプロジェクト内のアクティビティファイルを開き、ツールバーの「Run」アイコンをクリックします。接続中のモバイルデバイスを選択して実行すると、端末に次のような初期画面が表示されます。

Androidで音声をテキストに変換する方法|RecognizerIntentによる音声認識の実装手順

マイクボタンをタップすると、Googleの音声認識APIが呼び出され、以下のような音声入力画面に切り替わります。

Androidで音声をテキストに変換する方法|RecognizerIntentによる音声認識の実装手順

今回は「Hey GOOGLE」と話しかけてみました。認識が完了すると、結果がTextViewに反映されます。

Androidで音声をテキストに変換する方法|RecognizerIntentによる音声認識の実装手順

まとめ

RecognizerIntentを活用すれば、外部ライブラリを追加することなく、Android標準の仕組みだけで音声→テキスト変換機能を実装できます。メモアプリへの音声入力や音声検索など、さまざまな場面に応用できるので、ぜひ自分のプロジェクトでも試してみてください。

  1. Androidでテキストを読み上げさせる方法!Googleアシスタント・標準機能・おすすめアプリを徹底解説

    Androidデバイスは、ユーザーを驚かせる新機能を次々と搭載することで知られています。その最新のイノベーションのひとつが、画面を目で追って読むのではなく、テキストメッセージを「耳で聞く」ことを可能にする機能です。映画のトニー・スタークのようにバーチャルアシスタントにメッセージを読み上げてもらいたい方のために、本記事ではAndroidの標準テキスト読み上げ機能や、メッセージを読み上げてくれるアプリの使い方を詳しく解説します。Androidのテキスト読み上げ機能のメリットAndroidでメッセージを読み上げてもらう機能には、多くのメリットがあります。スマホを手に取って確認する必要がなく、デバイス

  2. 【Android】Googleテキスト読み上げ(TTS)の音声を変更する方法|声・言語・速度の設定手順

    Android端末のテキスト読み上げ(Text-to-Speech)の音声が聞き取りにくいと感じていませんか?この記事では、Googleテキスト読み上げ機能をより快適に活用できるよう、音声や設定をカスタマイズする方法をご紹介します。Androidには標準で「Google テキスト読み上げ」アプリが搭載されており、ユーザー補助(Accessibility)機能を使えば、画面上に表示されているテキストを読み上げてもらうことができます。複数の読み上げ音声から好みのものを選べるほか、サードパーティ製のテキスト読み上げアプリも多数存在します。 テキスト読み上げの音声とは? テキスト読み上げの音声とは、A