Playing a sound in pygame

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.

One thought on “Playing a sound in pygame

  1. Sir, my name Wian..
    Could I ask you some question?

    This’s about playing the sound using Python with Pygame..
    I’ve already did what you post here, I’ve changed the filename to my ‘real’ sound WAV name..
    Using quote ‘gameover.wav’ inside the bracket after the pygame.mixer.Sound() & the variable name after try:

    And the result it do nothing but the error appear because not using pygame.quit & sys.exit..

    What should I do then, I’m a newbie..
    Please guide me

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>