Skip to content

Instantly share code, notes, and snippets.

@RenaissanceBug
Created April 6, 2016 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RenaissanceBug/da7027d8c55a1819f9bae274e189ccac to your computer and use it in GitHub Desktop.
Save RenaissanceBug/da7027d8c55a1819f9bae274e189ccac to your computer and use it in GitHub Desktop.
Alternating between playing two WAV files using rsound
#lang racket
#|
Little audio player to demo switching between recordings with
the rsound library.
Create two .wav files, define your constants MUSIC-DIR, SONG1, SONG2,
and run in DrRacket.
Controls: press 1 to start looping SONG1, 2 to start looping SONG2,
or Esc to kill the audio.
|#
(require rsound
2htdp/universe 2htdp/image)
(define MUSIC-DIR "/path/to/my/wav-files/")
(define SONG1 (build-path MUSIC-DIR "a song.wav"))
(define SONG2 (build-path MUSIC-DIR "another song.wav"))
(define bgsong1 (rs-read SONG1))
(define bgsong2 (rs-read SONG2))
;; creates a pstream and starts playing the given rsound rs;
;; produces a thunk that stops playing by silencing the pstream
(define (play-rsound-loop rs #:init-volume [init-volume 0.3])
(define ps (make-pstream #:buffer-time 0.2))
(define len (rs-frames rs))
(define (loop)
(pstream-play ps rs)
(pstream-queue-callback ps loop (+ (pstream-current-frame ps) len)))
(thread loop)
(lambda ()
(pstream-set-volume! ps 0)
(void)))
;; demo with 2htdp/world
(struct world [current-track stop-audio] #:transparent)
(define (handle-key w ke)
(match w
[#f
(case ke
[("1") (world 1 (play-rsound-loop bgsong1))]
[("2") (world 2 (play-rsound-loop bgsong2))]
[else #f])]
[(world _ stop-audio)
(case ke
[("1")
(stop-audio)
(world 1 (play-rsound-loop bgsong1))]
[("2")
(stop-audio)
(world 2 (play-rsound-loop bgsong2))]
[("escape") (stop-audio) #f]
[else w])]))
(define BG (square 100 'solid 'red))
(define (draw w)
(match w
[(world track _)
(overlay (text (number->string track) 36 'yellow) BG)]
[_ BG]))
(big-bang #f
[to-draw draw]
[on-key handle-key])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment