Audio Assets
Check out https://freesound.org for a collaborative database of Creative Commons Licensed sounds.
Audio support is provided by the CPSound class.
An instance of CPSound class requires URI of the sound file in one of the supported formats: AIFF
, AU
or WAV
. Sound object is immutable but its playback can be controlled with changing volume, balance, rate, fade in and out. Sounds are inherently asynchronous objects, you can have many sounds objects, all of them are independent of each other, and you can play them in parallel.
Sound Is An Asset
Just like other assets such as CPFont, CPImage, CPParticleEmitter, CPAnimation or CPVideo they are not managed or governed by the CosPlay game engine unlike scenes and scene object, that are managed and governed by the game engine. Assets are typically created outside the game loop and managed by the developer, they can be freely shared between scenes or scene objects as any other standard Scala objects.
It is important to note that the game engine must be initialized by calling CPEngine.init(...) methods before sounds object can be created.
Sound objects are created in standard Scala way:
// Assuming all '*.wav' files are in default '/resources' folder. val sndBg = CPSound("background.wav") val sndWin = CPSound("win.wav") val sndLose = CPSound("lose.wav")
Once sounds object is created you can easily manipulate its playback. For example:
sndBg.loop(1500) // Starts indefinite loop with the one-time initial fade in. sndWin.play() // Plays the sounds once without a fade in.
For the scene-wide sounds like background music you can use lifecycle events of the scene or the lifecycle events of the special invisible scene object to start the playback. Here's an example of using scene's lifecycle events for that:
val bgPx = CPPixel('.', C_GREY1, C_GREY2) val dim = CPDim(100, 50) // Assuming all '*.wav' files are in default '/resources' folder. val sndBg = CPSound("background.wav") object MyScene extends CPScene("id", Option(dim), bgPx): private val spr1 = CPAnimationSprite(...) private val spr2 = CPAnimationSprite(...) addObjects(spr1, spr2) // Start the background audio when this scene activates. override def onActivate(): Unit = super.onActivate() sndBg.loop(1500) // 1.5sec fade in. // Stop the background audio when this scene deactivates. override def onDeactivate(): Unit = super.onDeactivate() sndBg.stop(1500) // 1.5sec fade out.
NOTES: