【Android】音声認識機能追加

動機

チャット部分で音声を言うと、それを認識してTextViewに入力する機能を実装したかったです。

参考


上記の資料を参考に、真似してみました。


始めましょう

1.fragment

class ChatFragment : Fragment(R.layout.chat_fragment) {

 private val REQUEST_CODE = 1000
   private val lang = 0

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

...
recognizer.setOnClickListener {
           speech()
       }

}

音声認識の形のボタンを押すと音声認識機能が実行されるようにしました。

2. speech()

 private fun speech() {
       // 音声認識のIntentインスタンス
       val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
       when (lang) {
           0 -> {
               // 日本語
               intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.JAPAN.toString())
           }
           1 -> {
               // 英語
               intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH.toString())
           }
           2 -> {
               // Off line mode
               intent.putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true)
           }
           else -> {
               intent.putExtra(
                   RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                   RecognizerIntent.LANGUAGE_MODEL_FREE_FORM
               )
           }
       }
       intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 100)
       intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "音声を入力")
       try {
           // インテント発行
           startActivityForResult(intent, REQUEST_CODE)
       } catch (e: ActivityNotFoundException) {
           e.printStackTrace()
           chat_text_view.text = "音声認識_error"
       }
   }

音声認識のIntentインスタンスを追加して

認識可能な言語と音声認識ダイヤログのタイトルを追加します

3. onActivityResult

    // 結果を受け取るために onActivityResult を設置
   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
       super.onActivityResult(requestCode, resultCode, data)
       if (requestCode == REQUEST_CODE) {
           // 認識結果を ArrayList で取得
           val candidates = data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
           candidates?.let {
               // 認識結果候補で一番有力なものを表示
               msgEditText.setText(candidates[0], TextView.BufferType.NORMAL)
           }
       }
   }

音声認識ダイアログで認識されたテキストを処理します。

4. 結果

画像1




この記事が気に入ったらサポートをしてみませんか?