TTSUtils.kt
2.03 KB
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
65
66
67
68
69
70
71
72
73
74
package com.tools.tts
import android.speech.tts.TextToSpeech
import android.speech.tts.TextToSpeech.OnInitListener
import android.speech.tts.UtteranceProgressListener
import android.util.Log
import com.tools.tts.common.TTSLibraryContext
import java.util.*
object TTSUtils {
private val onInitListener =
OnInitListener { status ->
Log.i("Test", "OnInitListener=$status")
ttsReady = status != TextToSpeech.ERROR
}
private val progressListener = object : UtteranceProgressListener() {
override fun onStart(utteranceId: String?) {
Log.i("Test", "onStart=$utteranceId")
isSpeak = true
}
override fun onDone(utteranceId: String?) {
Log.i("Test", "onDone=$utteranceId")
isSpeak = false
}
override fun onError(utteranceId: String?) {
Log.i("Test", "onError=$utteranceId")
isSpeak = false
}
override fun onStop(utteranceId: String?, interrupted: Boolean) {
Log.i("Test", "onStop=$utteranceId $interrupted")
isSpeak = !interrupted
super.onStop(utteranceId, interrupted)
}
}
val tts = TextToSpeech(
TTSLibraryContext.appContext,
onInitListener,
"com.diligrp.tms.kdy"
)
var ttsReady: Boolean = false
private var isSpeak: Boolean = false
init {
tts.setOnUtteranceProgressListener(progressListener)
}
fun sayText(text: String) {
val result = tts.setLanguage(Locale.SIMPLIFIED_CHINESE)
Log.e("Test", "sayText !")
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("Test", "setLanguage error! $result")
} else {
val speechResult =
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, Random().nextInt().toString())
Log.i("Test", "speechResult=$speechResult")
}
}
fun stop() {
tts.stop()
}
fun onCleared() {
tts.shutdown()
}
}