For the last couple of weeks I have been playing around with PySDL2 to learn a bit of game programming. Figuring that prototyping in Python was a good place to start learning, I originally planned to use Pygame which is a popular wrapper and extension of SDL. Now it seems that SDL (and Pygame) has been discontinued and PySDL2 looks to be the successor.
So far, using PySDL2 has been both easy and fun to create graphics and move them around, especially when using the extensions methods in sdl2.ext. But when adding sound to the mix, I hit upon a bit of trouble. For playing sounds it is necessary to use the SDL2 library functions. I decided to use a WAVE file (.wav) for my sound testing which meant using
SDL_LoadWav to load the file. PySDL2 uses a ctypes wrapper around the SDL2 library so that you can use the methods in almost the exact same way as from C code. This is both good and bad. The bad, at least for me, was that I had very little experience with ctypes and spent a lot of time figuring out how to declare the variables and types to use in the function calls. PySDL2 offer very little documentation on how to do it, and the SDL2 documentation doesn’t have too much example code on using
SDL_OpenAudio. After a lot of trying and failing I finally figured out a way that worked.
I also hit on a bug in the PySDL2 wrapper:
SDL_LoadWav is a macro that calls
SDL_LoadWav_RW wrapping the RWOPS part. What I found was that the PySDL2 macro uses wrong encoding of the mode string in the
SDL_RWFromFile call which makes
SDL_LoadWav fail. To make it work I had to call
SDL_RWFromFile myself as you see below. Also note the use of the compatibility method byteify() to convert the file name string to the encoding that
Here is the code:
I realize that I could have used SDL2_mixer for probably an easier way to do this, but I found this an interesting learning experience and worth sharing.
Update: I tried SDL2_mixer and it was much easier.