Skip to content

Instantly share code, notes, and snippets.

@nuhkoca
Created May 9, 2021 14:09
Show Gist options
  • Save nuhkoca/e632b50af313212f271f5c5cb9b68878 to your computer and use it in GitHub Desktop.
Save nuhkoca/e632b50af313212f271f5c5cb9b68878 to your computer and use it in GitHub Desktop.
TTS setup with any language
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.speech.tts.TextToSpeech.*
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import androidx.appcompat.app.AppCompatActivity
import com.example.ttsdemo.databinding.ActivityMainBinding
import java.util.*
class MainActivity : AppCompatActivity() {
private var _binding: ActivityMainBinding? = null
private val binding get() = _binding!!
private lateinit var textToSpeechEngine: TextToSpeech
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
textToSpeechEngine = TextToSpeech(this) { status ->
if (status == SUCCESS) {
val result = textToSpeechEngine.setLanguage(Locale("tr", "TR"))
if (result == LANG_MISSING_DATA || result == LANG_NOT_SUPPORTED) {
Toast.makeText(this, "Lang is not supported", LENGTH_LONG).show()
}
}
}
binding.btnSpeech.setOnClickListener {
val text = binding.etSpeech.text.toString().trim()
textToSpeechEngine.speak(text, QUEUE_FLUSH, null, "tts1")
}
}
override fun onPause() {
textToSpeechEngine.stop()
super.onPause()
}
override fun onDestroy() {
_binding = null
textToSpeechEngine.stop()
textToSpeechEngine.shutdown()
super.onDestroy()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment