Skip to content

Commit

Permalink
feat: early initialization of sound and TTS
Browse files Browse the repository at this point in the history
  • Loading branch information
ajmeese7 committed Sep 17, 2024
1 parent e56b896 commit d4782cb
Showing 1 changed file with 15 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,22 @@ class TimeUpdateWorker(
params: WorkerParameters
) : Worker(context, params), TextToSpeech.OnInitListener {

private lateinit var tts: TextToSpeech
private lateinit var soundPool: SoundPool
private var tts: TextToSpeech? = null
private var soundPool: SoundPool? = null
private var tickSoundId: Int = 0
private var isSoundLoaded: Boolean = false

init {
// Initialize TTS and SoundPool once
tts = TextToSpeech(applicationContext, this)
setupSoundPool()
}

override fun doWork(): Result {
val ticksEnabled = inputData.getBoolean("ticks_enabled", true)
val speechEnabled = inputData.getBoolean("speech_enabled", true)

if (ticksEnabled || speechEnabled) {
tts = TextToSpeech(applicationContext, this)
setupSoundPool()

val calendar = Calendar.getInstance()
val minute = calendar.get(Calendar.MINUTE)

Expand Down Expand Up @@ -53,35 +56,35 @@ class TimeUpdateWorker(
.setAudioAttributes(attributes)
.build()

soundPool.setOnLoadCompleteListener { _, _, status ->
soundPool?.setOnLoadCompleteListener { _, _, status ->
if (status == 0) {
isSoundLoaded = true
}
}

tickSoundId = soundPool.load(applicationContext, R.raw.tick_sound, 1)
tickSoundId = soundPool?.load(applicationContext, R.raw.tick_sound, 1) ?: 0
}

private fun speakTime(calendar: Calendar) {
val hour = calendar.get(Calendar.HOUR)
val minute = calendar.get(Calendar.MINUTE)
val amPm = if (calendar.get(Calendar.AM_PM) == Calendar.AM) "AM" else "PM"
val timeString = "$hour ${if (minute == 0) "o'clock" else minute} $amPm"
tts.speak(timeString, TextToSpeech.QUEUE_FLUSH, null, null)
tts?.speak(timeString, TextToSpeech.QUEUE_FLUSH, null, null)
}

private fun playTickSound() {
soundPool.play(tickSoundId, 1f, 1f, 1, 0, 1f)
soundPool?.play(tickSoundId, 1f, 1f, 1, 0, 1f)
}

override fun onInit(status: Int) {
if (status == TextToSpeech.SUCCESS) {
tts.language = Locale.US
tts?.language = Locale.US
}
}

override fun onStopped() {
tts.shutdown()
soundPool.release()
tts?.shutdown()
soundPool?.release()
}
}

0 comments on commit d4782cb

Please sign in to comment.