Sound & Music

From TRCCompSci - AQA Computer Science
Jump to: navigation, search


You must initialise the pygame mixer, this must be before you run pygame.init():

pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag
pygame.init() #initialize pygame

Loading Music & Sound

You can load music directly into the pygame mixer, however sound effects will need to variables:

# look for sound & music files in subfolder 'data''bakground.ogg')#load music
jump = pygame.mixer.Sound('jump.wav')  #load sound
die = pygame.mixer.Sound('die.wav')  #load sound

# play music non-stop

This could will play the music on an infinite loop.

Check if music is playing

We can use the built in method get_busy() to check if the music is currently playing:

    # indicate if music is playing
        print(" ... music is playing")
        print(" ... music is not playing")

Toggle Music

We can also use the built in stop() and play() methods to control the music:


Play Sound

Playing a sound is very easy, just use the play method of the sound you have loaded: