feat: 优化代码

pull/155/head^2
kunfei 5 years ago
parent 8cd18581a8
commit 8d5a1877aa
  1. 6
      app/src/main/java/io/legado/app/service/TTSReadAloudService.kt
  2. 38
      app/src/main/java/io/legado/app/ui/rss/read/ReadRssViewModel.kt

@ -29,7 +29,7 @@ class TTSReadAloudService : BaseReadAloudService(), TextToSpeech.OnInitListener
}
}
private var ttsIsSuccess: Boolean = false
private var ttsInitFinish = false
override fun onCreate() {
super.onCreate()
@ -47,7 +47,7 @@ class TTSReadAloudService : BaseReadAloudService(), TextToSpeech.OnInitListener
if (status == TextToSpeech.SUCCESS) {
textToSpeech?.language = Locale.CHINA
textToSpeech?.setOnUtteranceProgressListener(TTSUtteranceListener())
ttsIsSuccess = true
ttsInitFinish = true
play()
} else {
launch {
@ -58,7 +58,7 @@ class TTSReadAloudService : BaseReadAloudService(), TextToSpeech.OnInitListener
@Synchronized
override fun play() {
if (contentList.isEmpty() || !ttsIsSuccess) {
if (contentList.isEmpty() || !ttsInitFinish) {
return
}
if (requestFocus()) {

@ -35,7 +35,9 @@ class ReadRssViewModel(application: Application) : BaseViewModel(application),
val contentLiveData = MutableLiveData<String>()
val urlLiveData = MutableLiveData<AnalyzeUrl>()
var star = false
var textToSpeech: TextToSpeech = TextToSpeech(context, this)
var textToSpeech: TextToSpeech? = null
private var ttsInitFinish = false
private var ttsText = ""
fun initData(intent: Intent) {
execute {
@ -143,28 +145,42 @@ class ReadRssViewModel(application: Application) : BaseViewModel(application),
}
}
@Synchronized
override fun onInit(status: Int) {
launch {
if (status == TextToSpeech.SUCCESS) {
textToSpeech.language = Locale.CHINA
textToSpeech.setOnUtteranceProgressListener(TTSUtteranceListener())
} else {
if (status == TextToSpeech.SUCCESS) {
textToSpeech?.language = Locale.CHINA
textToSpeech?.setOnUtteranceProgressListener(TTSUtteranceListener())
ttsInitFinish = true
play()
} else {
launch {
toast(R.string.tts_init_failed)
}
}
}
@Synchronized
private fun play() {
if (!ttsInitFinish) return
textToSpeech?.stop()
ttsText.split("\n", " ", "  ").forEach {
textToSpeech?.speak(it, TextToSpeech.QUEUE_ADD, null, "rss")
}
}
fun readAloud(text: String) {
textToSpeech.stop()
text.split("\n", " ", "  ").forEach {
textToSpeech.speak(it, TextToSpeech.QUEUE_ADD, null, "rss")
ttsText = text
textToSpeech?.let {
play()
} ?: let {
textToSpeech = TextToSpeech(context, this)
}
}
override fun onCleared() {
super.onCleared()
textToSpeech.stop()
textToSpeech.shutdown()
textToSpeech?.stop()
textToSpeech?.shutdown()
}
/**

Loading…
Cancel
Save