leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Playing and stopping of Python Pygame sound

Estimated reading: 2 minutes 53 views

In games, we often need to set off an atmosphere through background music, or express a game state through some kind of sound effect. Many game programs use a lot of sound effects to express different events and states in the game, or play a role in some kind of prompting to the player.

Playing sounds from sound files is even easier than displaying images from image files. First, create a pygame.mixer.Sound object by calling the pygame.mixer.Sound() constructor. It accepts a string parameter, which is the filename of the sound file. Pygame can load WAV, MP3, or OGG types of sound files.

To play the sound, call the Sound object’s play() method. If you want to stop the playback of the Sound object immediately, call the stop() method. The stop() method has no parameters. code show as below.

import pygame
pygame.init()
windowSurface=pygame.display.set_mode([500,400])
music=pygame.mixer.Sound("sample.wav") 
music.play()
Running=True
while Running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Running =False
         if event.type == pygame.KEYDOWN: 
            if event.key == pygame.K_ESCAPE: 
                music.stop() 
pygame.quit()

In the highlighted code, we first initialize the mixer, then load a piece of background music, sample.wav, into a Sound object and store it in the variable music. Next, call the play() function to play the music. In addition, in the event loop, a judgment on keyboard events is added. If the Esc key is pressed, the stop() function is called to stop the music playback.

It should be noted that, like the image file, we need to save the sample.wav in the same folder as the program file, so that the program can find the file and use it, otherwise, we need to specify the path of the file.

Leave a Comment

CONTENTS