Play wave sound files with PyGame

vegaseat 2 Tallied Votes 2K Views Share

A simple code example on how to play wave sound files with the Python module PyGame.

''' pg_play_wav101.py
experiment with Pygame, play a few short wave files
'''

import os
import pygame

def load_sound(sound_filename, directory):
    """load the sound file from the given directory"""
    fullname = os.path.join(directory, sound_filename)
    sound = pygame.mixer.Sound(fullname)
    return sound
        
pygame.init()

# some color tuples (r,g,b)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

screen = pygame.display.set_mode([600, 400])
pygame.display.set_caption("Simple Play Wave Files")

# pick a wave (.wav) sound file you have in the given directory
directory = "C:/Windows/Media"
chimes = load_sound("chimes.wav", directory)
chord = load_sound("chord.wav", directory)
notify = load_sound("notify.wav", directory)

# optional color change
screen.fill(red)
pygame.display.flip()

chimes.play()
# milliseconds wait for each sound to finish
pygame.time.wait(2000)

screen.fill(green)
pygame.display.flip()

chord.play()

pygame.time.wait(2000)

screen.fill(blue)
pygame.display.flip()

notify.play()

# event loop and exit conditions
# escape key or display window x click
while True:
    for event in pygame.event.get():
        if (event.type == pygame.QUIT or 
            event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
            pygame.quit()
            raise SystemExit
aanchal_1 0 Newbie Poster

thank you for sharing the code.:)

juanpa_2510 0 Newbie Poster

pygame.mixer.Sound class is ideal for short wave (.wav) files that can be used as sound effects, you can play them as much as you want.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.