export default class TTS {
constructor() {
this.tts = null
this.listener = null
this.isInitialized = false
}
init() {
const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech')
const Locale = plus.android.importClass('java.util.Locale')
const main = plus.android.runtimeMainActivity()
this.tts = new TextToSpeech(main, new plus.android.implements(
'android.speech.tts.TextToSpeech$OnInitListener', {
onInit: (status) => {
if (status === TextToSpeech.SUCCESS) {
this.isInitialized = true
this.tts.setLanguage(Locale.CHINESE)
this.setSpeechRate(1.0)
this.setPitch(1.0)
console.log('TTS 引擎初始化成功')
} else {
console.error('TTS 引擎初始化失败')
}
}
}
))
}
speak(text) {
if (!this.isInitialized) {
console.error('TTS 引擎未初始化')
return
}
const TextToSpeech = plus.android.importClass('android.speech.tts.TextToSpeech')
this.tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, "utterance-id-001")
}
stop() {
if (this.isInitialized) {
this.tts.stop()
}
}
setSpeechRate(rate) {
if (this.isInitialized) {
this.tts.setSpeechRate(rate)
}
}
setPitch(pitch) {
if (this.isInitialized) {
this.tts.setPitch(pitch)
}
}
shutdown() {
if (this.isInitialized) {
this.tts.stop()
this.tts.shutdown()
this.isInitialized = false
}
}
getDefaultEngine() {
if (!this.tts) {
console.error('TTS 引擎未初始化')
return null
}
const engine = this.tts.getDefaultEngine()
return engine
}
getAllEngines() {
if (!this.tts) {
console.error('TTS 引擎未初始化')
return []
}
const engines = this.tts.getEngines()
const list = []
const size = plus.android.invoke(engines, 'size')
for (let i = 0; i < size; i++) {
const engineInfo = plus.android.invoke(engines, 'get', i)
const name = plus.android.getAttribute(engineInfo, 'name') + ''
const label = plus.android.getAttribute(engineInfo, 'label') + ''
list.push({ name, label })
}
return list
}
}