Skip to content

Instantly share code, notes, and snippets.

@illume
Last active July 14, 2019 11:37
Show Gist options
  • Save illume/f2fcdde9478aa3f1db8f3ee17359cf1c to your computer and use it in GitHub Desktop.
Save illume/f2fcdde9478aa3f1db8f3ee17359cf1c to your computer and use it in GitHub Desktop.
headless pygame (without a window) playing two sounds at different times.
""" headless pygame (without a window) playing two sounds one after the other.
"""
import os, sys, time
import pygame
import pygame.examples
# a pretend video.
os.environ["SDL_VIDEODRIVER"] = "dummy"
def pygame_example_data(fname):
return os.path.join(os.path.split(pygame.examples.__file__)[0], "data", fname)
file1 = pygame_example_data("boom.wav")
file2 = pygame_example_data("car_door.wav")
when_sound1 = 0.5
when_sound2 = 2.5
clock = pygame.time.Clock()
pygame.init()
screen = pygame.display.set_mode((1,1))
sound1 = pygame.mixer.Sound(file1)
sound2 = pygame.mixer.Sound(file2)
second_played = 0
FIRST = pygame.event.custom_type()
SECOND = pygame.event.custom_type()
# https://www.pygame.org/docs/ref/time.html#pygame.time.set_timer
# play things once...
pygame.time.set_timer(FIRST, int(when_sound1 * 1000), 1)
pygame.time.set_timer(SECOND, int(when_sound2 * 1000), 1)
going = True
while going:
for event in pygame.event.get():
if event.type == FIRST:
sound1.play()
if event.type == SECOND:
second_played = sound2.play()
if second_played and not second_played.get_busy():
going = False
# without this there is "Fatal Python error: PyEval_SaveThread: NULL tstate\nAbort trap: 6"
clock.tick(60)
# without this and second_played.get_busy() above there is a segfault.
time.sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment