Yesterday I wrote about playing a WAVE sound using basic PySDL2. I also mentioned that I thought that using the SDL2_mixer extension (or
sdl2.sdlmixer as it is called in PySDL2) would probably be easier. What I didn’t anticipate was how much easier it would be. Using
sdl2.sdlmixer more than halved the lines of code necessary to play the wav file, most importantly by removing the requirement to create a callback function to feed frames to the sound buffer.
The caveat is that you have to install the SDL2_mixer extension, of course. Just follow the instructions from the PySDL2 documentation, the simplest is to download the pre-built binaries. Then you have to make PySDL2 find the extension libraries. The installation guide talks about installing to the system or modifying
PYTHONPATH, but the preferred method is actually to store the libraries in a custom folder and setting
PYSDL2_DLL_PATH to the full path of that folder.
Once the extension is installed and working the code is simply this:
The code is simply initialize the audio system using standard
SDL_Init then initialize the mixer API with
Mix_OpenAudio before loading the wav file. This is different than the basic SDL2 API where you load the file first and then open the audio device. Finally, play the sound with
Mix_PlayChannel and wait until it has completed.