-
Notifications
You must be signed in to change notification settings - Fork 13
/
voice.rkt
117 lines (72 loc) · 2.77 KB
/
voice.rkt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#lang racket
#|
Racket Arcade (r-cade) - a simple game engine
Copyright (c) 2020 by Jeffrey Massung
All rights reserved.
|#
(require racket/match)
;; ----------------------------------------------------
(provide (all-defined-out))
;; ----------------------------------------------------
(struct voice [instrument envelope])
;; ----------------------------------------------------
(define basic-voice (voice sin (const 1)))
;; ----------------------------------------------------
(define sine-wave sin)
;; ----------------------------------------------------
(define (square-wave x)
(sgn (sin x)))
;; ----------------------------------------------------
(define (sawtooth-wave x)
(let ([y (/ x (* 2 pi))])
(* 2 (- y (floor (+ y 0.5))))))
;; ----------------------------------------------------
(define (triangle-wave x)
(- (* 2 (abs (sawtooth-wave x))) 1))
;; ----------------------------------------------------
(define (noise-wave x)
(* (square-wave x) (random)))
;; ----------------------------------------------------
(define-syntax synth
(syntax-rules ()
[(_ (f n) ...)
(let ([hs (list (λ (x) (* (f x) n)) ...)])
(λ (x)
(let ([w (for/sum ([wave hs] [m (in-naturals 1)])
(wave (* x m)))])
(min (max (* w) -1) 1))))]))
;; ----------------------------------------------------
(define (envelope y . ys)
(if (null? ys)
(const y)
; given [0,1] range, linear interpolate
(let* ([ys (list->vector (cons y ys))]
[n (- (vector-length ys) 1)])
(λ (s)
(cond
[(<= s 0.0) y]
; use last point
[(>= s 1.0) (vector-ref ys n)]
; linearly interpolate from u0 -> u1
[else (let* ([u (inexact->exact (floor (* s n)))]
[t (- (* s n) u)]
; from y0 -> y1
[y0 (vector-ref ys u)]
[y1 (vector-ref ys (+ u 1))])
(+ y0 (* t (- y1 y0))))])))))
;; ----------------------------------------------------
(define basic-envelope (const 1))
;; ----------------------------------------------------
(define fade-in-envelope (envelope 0 1))
;; ----------------------------------------------------
(define fade-out-envelope (envelope 1 0))
;; ----------------------------------------------------
(define z-envelope (envelope 1 1 0 0))
;; ----------------------------------------------------
(define s-envelope (envelope 0 0 1 1))
;; ----------------------------------------------------
(define peak-envelope (envelope 0 1 0))
;; ----------------------------------------------------
(define trough-envelope (envelope 1 0 1))
;; ----------------------------------------------------
(define adsr-envelope (envelope 0 1 0.7 0.7 0))