Uma biblioteca simples e eficiente que fornece funcionalidade de texto em fala para aplicativos Android.
Adicione a biblioteca ao seu projeto usando o gradle:
allprojects {
repositories {
maven { url ' https://jitpack.io ' }
}
}dependencies {
implementation ' com.github.aiyu-ayaan:tts-engine:Tag '
}O uso da biblioteca é direto e simples. Aqui está um exemplo de como usá -lo em seu 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 é a atividade que será usada para inicializar o mecanismo TTS.
owner é o proprietário do ciclo de vida que será usado para registrar o observador do ciclo de vida do motor TTS e pode lidar com os eventos do ciclo de vida.
message é o texto que será falado.
highlight() é um método opcional que destacará as palavras faladas no texto.
onHighlight() é um método opcional que será chamado quando uma palavra for falada.
onDone() é um método que será chamado quando o texto for falado.
onError() é um método que será chamado quando ocorrer um erro.
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() é um método de extensão que destaca as palavras faladas no texto. Method 1: registerLifecycle(owner: LifecycleOwner) Registre o ciclo de vida do proprietário fornecido.
Method 2: initTTS() inicializa o mecanismo de texto em fala.
Method 3: speak(message: String) gera discurso a partir da mensagem fornecida.
Method 4: highlight() destaca o texto no TextView.
Method 5: removeHighlight() remove o destaque do texto no TextView.
Method 6: destroy(action: (() -> Unit)) destrói o mecanismo de texto em fala e remove todos os ouvintes.
Method 7: onStart(onStartListener: () -> Unit) define o ouvinte OnStart.
Method 8: onDone(onCompleteListener: () -> Unit) define o ouvinte Ondone.
Method 9: onError(onErrorListener: (String) -> Unit) define o ouvinte OnError.
Method 10: onHighlight(onHighlightListener: (Pair<Int, Int>) -> Unit) define o ouvinte do OnHighlight.
Method 11: setCustomActionForDestroy(action: () -> Unit) define a ação personalizada a ser executada quando o mecanismo de texto em fala for destruído.
Method 12: setLanguage(locale: Locale) define o idioma para o mecanismo de texto em fala.
Method 13: setPitchAndSpeed(pitch: Float, speed: Float) define o passo e a velocidade da fala gerada pelo mecanismo de texto em fala.
Method 14: resetPitchAndSpeed() Redefine o passo e a velocidade da fala gerada pelo mecanismo de texto em fala para os valores padrão.
Se você deseja contribuir com a biblioteca, bifurque o repositório e crie uma solicitação de tração.
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.
`