Pygame Play Sounds Example

The pygame.mixer module provides several methods to play, pause, stop sounds. It supports a lot of sounds format files. This article will tell you how to use it to play multiple formats of sounds with examples.

1. Play Sounds In Pygame Steps.

  1. Create a Pygame sound object using the method pygame.mixer.Sound().
    audio = pygame.mixer.Sound(sound_file_path)
  2. Play the sound by invoking the audio object’s play(loops_number) method, the parameter loops_number is the number that this sound will be played, if you pass -1 to the parameter, the sound will be played indefinitely.
    audio.play(-1)
  3. Call the audio object’s stop() method to stop the sound.
    AUDIO_SOUND_PIANO.stop()
  4. If you want to play the sound until finished, then you can pause the game execution for some time to wait for the sound to play using the below source code.
    pygame.time.delay(time_out * 1000) 
         
    time.sleep(time_out)
  5. The method pygame.time.delay( time_out)‘s time_out parameter’s unit is milliseconds, so if you pass in second, then you should multiple the time_out parameter 1000 times.

2. Pygame Play Sounds Examples.

  1. In this pygame example, it will play a piano sound when the pygame application is running, and show the text Playing Piano Sound on the screen center.
  2. When you exit the pygame application, it will play an exit sound and show the text Playing Exit Sound, and exit the program until the exit sound is played finished.
  3. The python source file name PygamePlaySounds.py, below is the python file source code.
    '''
    Created on Feb 15, 2022
    
    @author: songzhao
    '''
    
    import pygame, sys, time
    
    # define 2 sounds path string variable.
    SOUND_FILE_EXIT = '../../../../sound/exit_ramp_open.wav'
    SOUND_FILE_PLAY_PIANO = '../../../../sound/piano-melody.mp3'
    
    # define the main window screen surface object.
    MAIN_WINDOW_SCREEN = None
    
    # define the piano sound audio object.
    AUDIO_SOUND_PIANO = None
    
    
    def initialize_pygame():
        
        pygame.init() 
        
        pygame.display.set_caption('Pygame Play Sound Example')
        
        global MAIN_WINDOW_SCREEN
        
        MAIN_WINDOW_SCREEN = pygame.display.set_mode((400, 400))
        
        # draw the text on the main screen window center.
        draw_play_sound_text('Playing Piano Sound')
        
        global AUDIO_SOUND_PIANO
        
        # play the piano sound.
        AUDIO_SOUND_PIANO = play(SOUND_FILE_PLAY_PIANO, 1)
    
    
    # this function can draw the text on the main window screen center.
    def draw_play_sound_text(text):
        
        global MAIN_WINDOW_SCREEN
        
        # clear the main window screen background by fill the white color.
        MAIN_WINDOW_SCREEN.fill(pygame.Color('white'))
        
        # get a text font from the system fonts.
        system_font = pygame.font.SysFont("signpainter", 36)
          
        # create a text surface object.    
        rendered_text = system_font.render(text, 0, (255, 100, 100))   
            
        # calculate the text surface object's top, left coordinates values.    
        rendered_text_x = (MAIN_WINDOW_SCREEN.get_width() - rendered_text.get_width())/2
        rendered_text_y = (MAIN_WINDOW_SCREEN.get_height() - rendered_text.get_height())/2   
            
        # draw the text surface object to the pygame main window screen center.    
        MAIN_WINDOW_SCREEN.blit(rendered_text, (rendered_text_x, rendered_text_y))
        
        # update the screen.
        pygame.display.update()
        
        
    # this function will play provided sound file and pause the game execution for time_out seconds.
    def play(sound_file_path, time_out):
        
        # create a Sound object.
        audio = pygame.mixer.Sound(sound_file_path) 
        
        # play the sound indefinitely.
        audio.play(-1)
        
        # pause the game execution for time_out seconds.
        pygame.time.delay(time_out * 1000) 
         
        time.sleep(time_out)
        
        return audio
        
        
    
    def main_loop():
        
        while True:
                    
            for event in pygame.event.get(): 
                
                if event.type == pygame.QUIT:
                    
                    # if user exit the application, then draw exit text on the main window screen center.
                    draw_play_sound_text('Playing Exit Sound')
                    
                    # stop playing the piano sound.
                    AUDIO_SOUND_PIANO.stop()
                    
                    # play the exit sound until finish.                
                    play(SOUND_FILE_EXIT, 5) 
                    
                    pygame.quit() 
                    
                    sys.exit()
                    
            pygame.display.update()
    
    
    if __name__ == '__main__':
        
        initialize_pygame()
        
        main_loop()
        
    

3. Pygame Play Sounds Example Demo Video.

  1. The demo video for this example is https://youtu.be/trjm5zKK_Po.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.