A simple code example on how to play wave sound files with the Python module PyGame.
Play wave sound files with 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
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.