Skip to content

Instantly share code, notes, and snippets.

@shadowmint
Created October 11, 2013 02:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save shadowmint/6928668 to your computer and use it in GitHub Desktop.
Save shadowmint/6928668 to your computer and use it in GitHub Desktop.
SDL2 mixer example
import ctypes
import unittest
import time
import os.path
from sdl2 import *
from sdl2.sdlmixer import *
class MixerTests(unittest.TestCase):
def test_mixer(self):
if SDL_Init(SDL_INIT_VIDEO) != 0:
print(SDL_GetError())
return -1
if Mix_Init(MIX_INIT_MP3) == -1:
print(Mix_GetError())
return -1
if Mix_OpenAudio(22050, MIX_DEFAULT_FORMAT, 2, 1024) == -1:
print(Mix_GetError())
return -1
window = SDL_CreateWindow(b"Text", SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED, 100, 100,
SDL_WINDOW_SHOWN)
if not window:
print(SDL_GetError())
return -1
Mix_AllocateChannels(0)
sound = Mix_LoadMUS(b"assets/song2.mp3")
try:
sound.contents
except ValueError:
print(Mix_GetError())
return -1
if Mix_PlayMusic(sound, 1) == -1:
print(Mix_GetError())
return -1
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)
event = SDL_Event()
running = True
start_time = time.time()
while running:
while SDL_PollEvent(ctypes.byref(event)) != 0:
if event.type == SDL_QUIT:
running = False
if time.time() - start_time > 1:
running = False
Mix_FreeMusic(sound)
SDL_DestroyRenderer(renderer)
SDL_DestroyWindow(window)
Mix_CloseAudio()
Mix_Quit()
SDL_Quit()
if __name__ == "__main__":
unittest.main()
@iacopy
Copy link

iacopy commented Jul 10, 2016

Thanks for sharing but it's not actually testing anything about actual playing because there are no assertions.
Errors are intercepted but do not make the test fail. I have the test passing with 'unrecognised music format' error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment