Playing a sound in pygame

Sun 24 February 2008
By stu

It can be useful to test sounds in your current engine (esp for testing MOD support), so I've made a tiny sound player for pygame. The code is just this:

import sys, pygame
from pygame.locals import *

import pygame.mixer

if __name__=="__main__":
    pygame.display.set_mode((120, 120), DOUBLEBUF | HWSURFACE)

    pygame.init()

    try:
        filename = sys.argv[1]
        pygame.mixer.init()
        sound = pygame.mixer.Sound(filename)
        print 'Press ESC to quit, any other key retriggers sound'
        sound.play()

        running = True
        while running:
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == K_ESCAPE:
                        running = False
                    else:
                        sound.play()

    except IndexError:
        print 'Usage tplay.py filename'

The file is attached here: Tiny pygame audio player.