Android 文本转语音开发
提示:本系列文章处于动态更新当中; 由于本人是通过网络渠道自学的Android, 一些原理的解释和代码仅代表我个人观点.
1、原生案例.
不需要xml文件, 代码直接复制到Activity中就行了.
package com.example.excute
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.view.Gravity
import android.view.View
import android.widget.LinearLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatEditText
import java.util.Locale
class 优快云Activity : AppCompatActivity(), TextToSpeech.OnInitListener {
private lateinit var tts: TextToSpeech
private lateinit var ll: LinearLayout
private lateinit var editText: AppCompatEditText
private lateinit var speakButton: AppCompatButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.ll = LinearLayout(this).also {
this.setContentView(it)
it.orientation = LinearLayout.VERTICAL
var param: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
0,
1.0F
)
for (i in 0 until 7) {
if (i == 2) {
this.editText = AppCompatEditText(this).apply {
layoutParams = param
gravity = Gravity.CENTER
hint = "Enter your sentence"
}
it.addView(this.editText)
}
else if (i == 4) {
this.speakButton = AppCompatButton(this).apply {
layoutParams = param
gravity = Gravity.CENTER
text = "SPEAK"
}
it.addView(this.speakButton)
}
else {
val view: View = View(this).apply {
layoutParams = param
}
it.addView(view)
}
}
}
this.tts = TextToSpeech(this, this)
this.speakButton.setOnClickListener {
val text = this.editText.text.toString().trim()
if (text.isNotEmpty()) {
this.speakText(text)
} else {
Toast.makeText(this, "Please enter text to speak", Toast.LENGTH_SHORT).show()
}
}
}
private fun speakText(text: String): Unit {
this.tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, "")
}
override fun onInit(status: Int) {
if (status == TextToSpeech.SUCCESS) {
val result = this.tts.setLanguage(Locale.CHINA)
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(this, "Language not supported", Toast.LENGTH_SHORT).show()
}
}
}
override fun onDestroy() {
if (this.tts.isSpeaking) {
this.tts.stop()
}
this.tts.shutdown()
super.onDestroy()
}
}