Skip to content

Commit

Permalink
backgroundAudio convenience function
Browse files Browse the repository at this point in the history
  • Loading branch information
byerlyb20 committed Jul 16, 2024
1 parent bd9f36a commit da2f555
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,37 +32,7 @@ object AudioScreen : Screen {
text("Background sound")
}

val backgroundAudioShared = shared {
Resources.audioTaunt.load().apply { volume = 0.1f }
}
// Loop and cancel the background sound
reactiveScope {
if (backgroundSoundPlaying()) {
val backgroundAudio = backgroundAudioShared()
suspendCoroutineCancellable<Unit> {
backgroundAudio.onComplete {
backgroundAudio.play()
}
return@suspendCoroutineCancellable {
backgroundAudio.stop()
}
}
}
}
// Trigger the background sound once every five seconds until it successfully starts
reactiveScope {
if (backgroundSoundPlaying()) {
val backgroundAudio = backgroundAudioShared()
while (true) {
if (!backgroundAudio.isPlaying) {
backgroundAudio.play()
delay(5000)
} else {
break
}
}
}
}
backgroundAudio(Resources.audioTaunt) { backgroundSoundPlaying() }
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package com.lightningkite.kiteui

import com.lightningkite.kiteui.models.AudioResource
import com.lightningkite.kiteui.models.AudioSource
import com.lightningkite.kiteui.reactive.invoke
import com.lightningkite.kiteui.reactive.shared
import com.lightningkite.kiteui.views.RView
import com.lightningkite.kiteui.views.reactiveScope

expect class SoundEffectPool(concurrency: Int = 4) {
suspend fun preload(sound: AudioSource)
Expand All @@ -25,3 +30,37 @@ interface PlayableAudio {
isPlaying = true
}
}

fun RView<*>.backgroundAudio(audio: AudioResource, playBackgroundAudio: suspend () -> Boolean) {
val backgroundAudioShared = shared {
audio.load().apply { volume = 0.1f }
}
// Loop and cancel the background sound
reactiveScope {
if (playBackgroundAudio()) {
val backgroundAudio = backgroundAudioShared()
suspendCoroutineCancellable<Unit> {
backgroundAudio.onComplete {
backgroundAudio.play()
}
return@suspendCoroutineCancellable {
backgroundAudio.stop()
}
}
}
}
// Trigger the background sound once every five seconds until it successfully starts
reactiveScope {
if (playBackgroundAudio()) {
val backgroundAudio = backgroundAudioShared()
while (true) {
if (!backgroundAudio.isPlaying) {
backgroundAudio.play()
delay(5000)
} else {
break
}
}
}
}
}

0 comments on commit da2f555

Please sign in to comment.