Sound & Music

From TRCCompSci - AQA Computer Science
Revision as of 10:20, 5 July 2018 by Admin (talk | contribs) (Created page with "=Setup= You must initialise the pygame mixer, this must be before you run pygame.init(): <syntaxhighlight lang=python> pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixe...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Setup

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'
pygame.mixer.music.load('bakground.ogg')#load music
jump = pygame.mixer.Sound('jump.wav')  #load sound
die = pygame.mixer.Sound('die.wav')  #load sound

# play music non-stop
pygame.mixer.music.play(-1)

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
    if pygame.mixer.music.get_busy():
        print(" ... music is playing")
    else: 
        print(" ... music is not playing")

Toggle Music

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

        if pygame.mixer.music.get_busy():
            pygame.mixer.music.stop()
        else:
            pygame.mixer.music.play()

Play Sound

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

jump.play()
die.play()