Making a Soundboard in Emacs

While I’m running a role playing game, I really like having music and audio effects playing. I’ve noticed I can’t have very many apps running… I essentially want Emacs displaying my notes and—that’s it. So why not see if I can’t make a soundboard, a way to play music tracks and audio files easily.

Playing Sounds

Seems like my first step is to have a function that can play an audio file, but abstracted, so it can work with either my Mac or Linux system.

(defun soundboard-play (file &rest options)
  "Play an audio FILE.
Any additional parameters affect how the audio should be played.
  - `:repeat' a integer number of times to play the FILE.
  - `:until' replace audio until variable given is t."
  (message "%s" options)
  (cond
   ((plist-get :repeat options) (soundboard-play-repeat file))
   ((plist-get :until options) (message "Doing until"))
   (t                          (soundboard--play-audio file 'ignore))))

(soundboard-play "bubba" :until 'isay)

(defun soundboard-play-repeat (file repeat)
  "Play audio FILE a number of REPEAT times."
  (when (> repeat 0)
    (soundboard--play-audio file
                            (lambda (ignored)
                              (soundboard-play-repeat file (1- repeat))))))

(defun soundboard--play-audio (file callback)
  "Play an audio FILE, and call CALLBACK when finished."
  (lexical-let ((command (if (equal system-type 'darwin)
                     (format "afplay %s" file)
                   (format "aplay %s" file))))
    (async-start
     (lambda ()
       (shell-command command "*soundboard-results*"))
     callback)))

(soundboard--play-audio "afplay ~/Downloads/fountain.wav" 'ignore)

(shell-command "afplay ~/Downloads/fountain.wav")