-
Notifications
You must be signed in to change notification settings - Fork 0
/
TextReader.kt
64 lines (52 loc) · 1.74 KB
/
TextReader.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
object TextReader {
private var textToSpeech: TextToSpeech? = null
private var isReady : Boolean = false
private var utteranceInProgress = MutableStateFlow(SpeechState.INITIALIZE)
val utteranceInProgressFlow = utteranceInProgress.asStateFlow()
fun read(text : String){
textToSpeech?.speak(
text ,
TextToSpeech.QUEUE_FLUSH ,
null ,
"quote")
}
fun initialize(context: Context){
textToSpeech?.let {
return
}
val speechListener = TextToSpeech.OnInitListener {
if(it == TextToSpeech.SUCCESS) {
textToSpeech?.language = Locale.US
textToSpeech?.setSpeechRate(1.1f)
val utteranceListener = object : UtteranceProgressListener(){
override fun onStart(utteranceId: String?) {
utteranceInProgress.value = SpeechState.SPEAKING
}
override fun onDone(utteranceId: String?) {
utteranceInProgress.value = SpeechState.COMPLETE
}
@Deprecated("Deprecated in Java")
override fun onError(utteranceId: String?) {}
}
textToSpeech?.setOnUtteranceProgressListener(utteranceListener)
isReady = true
}
}
textToSpeech = TextToSpeech(context , speechListener)
}
fun check(context: Context){
if(isReady) return
initialize(context)
}
fun destroy(){
textToSpeech?.shutdown()
textToSpeech = null
isReady = false
}
fun stop(){
textToSpeech?.stop()
}
fun reset(){
utteranceInProgress.value = SpeechState.INITIALIZE
}
}