How to create Text to Speech in an Android App using Kotlin?

This example demonstrates how to create Text to Speech in an Android App using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.



   
   
   
   
   
   
   

Step 3 − Add the following code to MainActivity.kt

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.speech.RecognizerIntent
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.*
import kotlin.collections.ArrayList
class MainActivity : AppCompatActivity() {
   private val REQUESTCODE = 100
   lateinit var textView: TextView
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      textView = findViewById(R.id.textView)
      val speakImageView: ImageView = findViewById(R.id.speakImageView)
      speakImageView.setOnClickListener {
         val intent = 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, "Need to Speak")
         startActivityForResult(intent, REQUESTCODE)
         Toast.makeText(applicationContext, "Sorry your device not supported", Toast.LENGTH_SHORT).show()
      }
   }
   override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
      super.onActivityResult(requestCode, resultCode, data)
      if (resultCode == Activity.RESULT_OK && null != data) {
         val result: ArrayList = data.getStringArrayListExtra(RecognizerIntent .EXTRA_RESULTS) textView.text = result[0]
      }
   }
}

Step 4 − Add the following code to androidManifest.xml



   
      
         
            
            
         
      
   

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −

NOTE− Test in your own device for better results

Click here to download the project code.

Updated on: 2020-04-21T09:27:56+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements