Una biblioteca simple y eficiente que proporciona funcionalidad de texto a voz para aplicaciones de Android.
Agregue la biblioteca a su proyecto usando Gradle:
allprojects {
repositories {
maven { url ' https://jitpack.io ' }
}
}dependencies {
implementation ' com.github.aiyu-ayaan:tts-engine:Tag '
}Usar la biblioteca es sencillo y simple. Aquí hay un ejemplo de cómo usarlo en su código:
TextToSpeechHelper
.getInstance(activity)
.registerLifecycle(owner)
.speak(message)
.highlight()
.onHighlight { pair ->
Log .d( TAG , " speak: ${pair.first} - ${pair.second} " )
}
.onDone {
Log .d( TAG , " speak: done " )
}
.onError {
Log .d( TAG , " speak: $it " )
} activity es la actividad que se utilizará para inicializar el motor TTS.
owner es el propietario del ciclo de vida que se utilizará para registrar el observador del ciclo de vida del motor TTS y puede manejar los eventos del ciclo de vida.
message es el texto que se hablará.
highlight() es un método opcional que resaltará las palabras habladas en el texto.
onHighlight() es un método opcional que se llamará cuando se pronuncia una palabra.
onDone() es un método que se llamará cuando se habla el texto.
onError() es un método que se llamará cuando ocurra un error.
MainActivity.kt
class MainActivity : ComponentActivity () {
override fun onCreate ( savedInstanceState : Bundle ? ) {
super .onCreate(savedInstanceState)
setContent {
TTSLibraryTheme {
val viewModel = MainViewModel ()
val resource = stringResource(id = R .string.des)
val text = remember { resource }
// screen
Surface (
modifier = Modifier .fillMaxSize(),
color = MaterialTheme .colorScheme.background
) {
Screen (
state = text,
viewModel = viewModel,
) {
speak(
this ,
this as LifecycleOwner ,
text,
viewModel
)
}
}
}
}
}
}
@Composable
fun Screen (
modifier : Modifier = Modifier ,
viewModel : MainViewModel ,
state : String ,
onButtonClick : () -> Unit = {},
) {
Column (
modifier = modifier
.fillMaxSize()
.padding( 16 .dp),
verticalArrangement = Arrangement . Center ,
horizontalAlignment = Alignment . CenterHorizontally
) {
val s = viewModel.getState().value
TTSText (
textAlign = TextAlign . Center ,
textHighlightBuilder = TextHighlightBuilder (
text = state,
s
),
)
Spacer (modifier = Modifier .padding( 16 .dp))
Button (onClick = onButtonClick) {
Text (text = stringResource(id = R .string.speak))
}
}
}
private fun speak (
activity : Activity ,
owner : LifecycleOwner ,
message : String ,
viewModel : MainViewModel
) {
TextToSpeechHelper
.getInstance(activity)
.registerLifecycle(owner)
.speak(message)
.highlight()
.onHighlight { pair ->
viewModel.updateState(pair)
}
.onDone {
Log .d( TAG , " speak: done " )
}
.onError {
Log .d( TAG , " speak: $it " )
}
}
MainViewModel.kt
class MainViewModel : ViewModel () {
private val state = mutableStateOf( Pair ( 0 , 0 ))
fun updateState ( pair : Pair < Int , Int >) {
state.value = pair
}
fun getState (): State < Pair < Int , Int >> = state
} class MainActivity : AppCompatActivity () {
override fun onCreate ( savedInstanceState : Bundle ? ) {
super .onCreate(savedInstanceState)
setContentView( R .layout.activity_main)
val textView = findViewById< TextView >( R .id.text_view)
val button = findViewById< Button >( R .id.button)
val message = getString( R .string.des)
button.setOnClickListener {
speak(
this ,
this as LifecycleOwner ,
message,
textView
)
}
}
private fun speak (
activity : Activity ,
owner : LifecycleOwner ,
message : String ,
textView : TextView
) {
TextToSpeechHelper
.getInstance(activity)
.registerLifecycle(owner)
.speak(message)
.highlight()
.onHighlight { pair ->
textView.highlightText(pair.first, pair.second)
}
.onDone {
Log .d( TAG , " speak: done " )
}
.onError {
Log .d( TAG , " speak: $it " )
}
}
}TextView.highlightText() es un método de extensión que resalta las palabras habladas en el texto. Method 1: registerLifecycle(owner: LifecycleOwner) registra el ciclo de vida del propietario dado.
Method 2: initTTS() inicializa el motor de texto a voz.
Method 3: speak(message: String) genera discurso desde el mensaje dado.
Method 4: highlight() resalta el texto en TextView.
Method 5: removeHighlight() Elimina el resaltado del texto en el TextView.
Method 6: destroy(action: (() -> Unit)) destruye el motor de texto a voz y elimina a todos los oyentes.
Method 7: onStart(onStartListener: () -> Unit) Establece el oyente ONStart.
Method 8: onDone(onCompleteListener: () -> Unit) Establece el oyente de Ondone.
Method 9: onError(onErrorListener: (String) -> Unit) Establece el oyente de OnError.
Method 10: onHighlight(onHighlightListener: (Pair<Int, Int>) -> Unit) Establece el oyente de OnHighlight.
Method 11: setCustomActionForDestroy(action: () -> Unit) Establece la acción personalizada que se realizará cuando se destruye el motor de texto a voz.
Method 12: setLanguage(locale: Locale) Establece el idioma para el motor de texto a voz.
Method 13: setPitchAndSpeed(pitch: Float, speed: Float) Establece el tono y la velocidad del discurso generado por el motor de texto a voz.
Method 14: resetPitchAndSpeed() restablece el tono y la velocidad del discurso generado por el motor de texto a voz a los valores predeterminados.
Si desea contribuir a la biblioteca, bifurca el repositorio y crea una solicitud de extracción.
MIT License
Copyright (c) 2023 Ayaan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
`