
(libload "libc/libc")
(libload "audiofile/audiofile")
(libload "alsa/alsa")

(setq wave (audiofile-read (concat-fname lushdir "packages/audiofile/demos/space.wav")))

(de play-wave (wave)
  (let* ((psndhandle-idx (gptr-matrix))
	 (device "default")
	 (hwhandle-idx (ubyte-matrix (snd_pcm_hw_params_sizeof)))
	 (hwhandle (idx-ptr hwhandle-idx)))
    (snd_pcm_open (idx-ptr psndhandle-idx) device @@SND_PCM_STREAM_PLAYBACK 0)
    (let ((sndhandle (psndhandle-idx)))
      (when (= () sndhandle) (error "could not open Alsa device"))
      ;; start setup hardware parameters
      (snd_pcm_hw_params_any              sndhandle hwhandle)
      (snd_pcm_hw_params_set_access       sndhandle hwhandle @@SND_PCM_ACCESS_RW_INTERLEAVED)
      (snd_pcm_hw_params_set_format       sndhandle hwhandle @@SND_PCM_FORMAT_S16_LE)
      (snd_pcm_hw_params_set_channels     sndhandle hwhandle 2)
      (snd_pcm_hw_params_set_rate_near    sndhandle hwhandle 44100 (gptr ()))
      (snd_pcm_hw_params_set_periods      sndhandle hwhandle 2 0)
      (snd_pcm_hw_params_set_buffer_time_near sndhandle hwhandle 500000 (gptr ()))
      (snd_pcm_hw_params                  sndhandle hwhandle)
      (snd_pcm_writei sndhandle (idx-ptr wave) (idx-dim wave 0))
      (snd_pcm_close  sndhandle)
      (afCloseFile fhandle))))

