yue

Programmatic music library

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
(use-modules (ice-9 binary-ports))

; Bitrate is the number time to sample the music function each second
(define bitrate 8000)

; Triangle wave with a period of 1 second
(define (tri t)
	(let ((m (floor-remainder (+ t (/ 1 4)) 1)))
		(if (< m 1/2)
			(- (* 4 m) 1)
			(- 3 (* 4 m)))))

; Square wave with a period of 1 second
(define (square t)
	(let ((m (floor-remainder t 1)))
		(if (< m 0.5) 1 -1)))

; Creates a note
(define (note freq start len)
	(lambda (t) (
		if (or (< t start) (>= t (+ start len)))
			0
			(* 1/4 (tri (* t freq))))))

; Gets the frequency of a particular pitch
(define (getfreq octave pitch)
	(* 55 (ash 1 octave) (expt 2 (/ pitch 12))))

; Get the music as a list sampled at the bitrate
(define (play t end)
	(cons ((lambda (a)
		(let ((b (modulo (inexact->exact (round (* (+ a 2) 32768))) 65536))) cons
			(put-u8 (current-output-port) (modulo b 256))
			(put-u8 (current-output-port) (quotient b 256)))) (music t))
		(if (< t end)
			(play (+ t (/ 1 bitrate)) end)
			'())))