1. #Demo: audio support via core SDL2 and LoadWAV (complicate, use SDL2_mixer instead)
  2.  
  3. from os import path
  4. import sys
  5. from ctypes import *
  6.  
  7. try:
  8.     from sdl2 import *
  9.     from sdl2.ext.compat import byteify
  10. except ImportError:
  11.     import traceback
  12.     traceback.print_exc()
  13.     sys.exit(1)
  14.  
  15. class WavSound(object):
  16.     def __init__(self, file):
  17.         super(WavSound, self).__init__()
  18.         self._buf = POINTER(Uint8)()
  19.         self._length = Uint32()
  20.         self._bufpos = 0
  21.         self.spec = SDL_AudioSpec(0, 0, 0, 0)
  22.         self._load_file(file)
  23.         self.spec.callback = SDL_AudioCallback(self._play_next)
  24.         self.done = False
  25.  
  26.     def __del__(self):
  27.         SDL_FreeWAV(self._buf)
  28.  
  29.     def _load_file(self, file):
  30.         rw = SDL_RWFromFile(byteify(file, "utf-8"), b"rb")
  31.         sp = SDL_LoadWAV_RW(rw, 1, byref(self.spec), byref(self._buf), byref(self._length))
  32.         if sp is None:
  33.             raise RuntimeError("Could not open audio file: {}".format(SDL_GetError()))
  34.  
  35.     def _play_next(self, notused, stream, len):
  36.         length = self._length.value
  37.         numbytes = min(len, length - self._bufpos)
  38.         for i in range(0, numbytes):
  39.             stream[i] = self._buf[self._bufpos + i]
  40.         self._bufpos += numbytes
  41.  
  42.         # If not enough bytes in buffer, add silence
  43.         rest = min(0, len - numbytes)
  44.         for i in range(0, rest):
  45.             stream[i] = 0
  46.  
  47.         # Are we done playing sound?
  48.         if self._bufpos == length:
  49.             self.done = True
  50.  
  51. def main():
  52.     if SDL_Init(SDL_INIT_AUDIO) != 0:
  53.         raise RuntimeError("Cannot initialize audio system: {}".format(SDL_GetError()))
  54.  
  55.     sound = WavSound(path.realpath('.')+"/assets/test.wav")
  56.  
  57.     devid = SDL_OpenAudioDevice(None, 0, sound.spec, None, SDL_AUDIO_ALLOW_FORMAT_CHANGE)
  58.     if devid == 0:
  59.         raise RuntimeError("Unable to open audio device: {}".format(SDL_GetError()))
  60.  
  61.     SDL_PauseAudioDevice(devid, 0)
  62.     while not sound.done:
  63.         SDL_Delay(100)
  64.     SDL_CloseAudioDevice(devid)
  65.  
  66.     SDL_Quit(SDL_INIT_AUDIO)
  67.  
  68. if __name__ == '__main__':
  69.     main()
  70.  
[raw code]