Friday, January 4, 2008

Some pygame examples for audiogame programming

While there are tutorials for pygame, they often contain graphic examples. So I have started to write some very simple examples focused on audiogames programming.

To use this tutorial, you should already know Python. The Python tutorial is a good start; there is Dive into Python too. To run the examples, you must have Python and pygame installed.

You can download all the examples (with the sounds) here.

Example 1: play a sound and change its stereo position


The example 1 shows how to play a sound and pan it. To go further:
Edit: warning! nowadays, it might be necessary to initialize the display or no sound will be heard! for example: pygame.display.set_mode((200,100))

# example1.py
# play a sound to the left, to the right and to the center

# import the time standard module
import time

# import the pygame module
import pygame


# start pygame
pygame.init()

# load a sound file into memory
sound = pygame.mixer.Sound("bird.ogg")

# start playing the sound
# and remember on which channel it is being played
channel = sound.play()
# set the volume of the channel
# so the sound is only heard to the left
channel.set_volume(1, 0)
# wait for 1 second
time.sleep(1)

# do the same to the right
channel = sound.play()
channel.set_volume(0, 1)
time.sleep(1)

# do the same to the center
channel = sound.play()
channel.set_volume(1, 1)
time.sleep(1)



Example 2: read keyboard events


The example 2 shows how to read events from the keyboard. To go further:

# example2.py
# start playing a sound when a key is pressed
# exit if the letter "q" or the "escape" key is pressed

# import the pygame module
import pygame


# start pygame
pygame.init()

# load a sound file into memory
sound = pygame.mixer.Sound("bird.ogg")

# start the display (required by the event loop)
pygame.display.set_mode((320, 200))

# loop forever (until a break occurs)
while True:
  # wait for an event
  event = pygame.event.wait()
  # if the event is about a keyboard button that have been pressed...
  if event.type == pygame.KEYDOWN:
      # ... then start playing the sound
      sound.play()
      # and if the button is the "q" letter or the "escape" key...
      if event.unicode == "q" or event.key == pygame.K_ESCAPE:
          # ... then exit from the while loop
          break

That's all for the moment!