Sounds can be loaded from WAV or Ogg Vorbis files with the Sound class. Once loaded, you can play a sound as “one-shot” effect by calling Sound.play():
import bacon
sound = bacon.Sound('res/ball.wav')
class Game(bacon.Game):
def on_tick(self):
bacon.clear(0, 0, 0, 1)
def on_key(self, key, pressed):
if pressed:
sound.play()
bacon.run(Game())
Playing looping music, or longer-lasting sound effects like engine sounds, is best done with a Voice. A Voice is a particular instance of a sound playing. For example, if you play the same ball.wav sound effect three times, you have used three voices, whether or not the sounds are playing all at once or one after another.
The following example demonstrates a looping music track. The track’s pan varies based on the position of the mouse in the window, and it can be paused and resumed with the spacebar:
import bacon
# Load the music file, set stream=True since this is a long file that should be
# streamed from disk
music = bacon.Sound('res/PowerChorus2.ogg', stream=True)
# Create an instance of the music and start playing it
music_voice = bacon.Voice(music, loop=True)
music_voice.play()
class Game(bacon.Game):
def on_tick(self):
bacon.clear(0, 0, 0, 1)
# Change the pan of the music based on the mouse position
music_voice.pan = bacon.mouse.x / bacon.window.width * 2 - 1
def on_key(self, key, pressed):
# Pressing spacebar pauses/resumes the music
if key == bacon.Keys.space and pressed:
music_voice.playing = not music_voice.playing
bacon.run(Game())