1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Android】テキスト読み上げ機能 TextToSpeech【kotlin】

Posted at

はじめに

ここ最近の記事では音に関しての記事を書くことが多いですが、他にもないか調べていたところ
テキスト読み上げ機能である TextToSpeechというものを見つけたのでそれについて記事にしたいと思います。

TextToSpeech

まずはじめに このテキスト読み上げ機能TextToSpeechを使用するにはOnInitListenerインターフェースを継承する必要があります。

TextToSpeechの第一引数にはContext、第二引数にはListenerを渡します。
継承したonInitメソッドで言語を日本に設定します。

MainActivity.kt
class MainActivity : AppCompatActivity() , TextToSpeech.OnInitListener{
    private var textToSpeech: TextToSpeech? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textToSpeech = TextToSpeech(this, this)
    }

    override fun onInit(p0: Int) {
        textToSpeech?.language = Locale.JAPAN
    }
}

ここまで設定できたら ボタンが押されたときにテキストを読み上げるようにします
speakの第一引数にはtext:読み上げたいテキスト、
第二引数にはqueueMode:使用するキューイング QUEUE_FLUSHかQUEUE_ADD を指定
QUEUE_FLUSHに指定しておけば、すぐに読み上げられる
第三引数にはparams:パラメータとしてbundleを渡せる オーディオ ストリーム タイプや音量を指定できる

        val button: Button = findViewById<Button>(R.id.button)

        button.setOnClickListener(){
            textToSpeech!!.speak("ハローワールド", TextToSpeech.QUEUE_FLUSH, null)
        }

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?