DayByDay/Sound/SoundSynth.swift
385 lines · 16658 bytes
24 symbols in this file
1//
2// SoundSynth.swift
3// DayByDay
4//
5
6import Foundation
7
8nonisolated enum SoundEffect: Hashable, CaseIterable, Sendable {
9 case success, gentleMiss, roundComplete
10 case moo, quack, baa, oink, meow, woof, tweet
11 case rain, wind, thunder
12 /// Two-tone train whistle, for a finished week train.
13 case whistle
14 /// That many short beeps, for counting.
15 case beeps(Int)
16
17 static let allCases: [SoundEffect] =
18 [.success, .gentleMiss, .roundComplete, .moo, .quack, .baa, .oink, .meow, .woof, .tweet,
19 .rain, .wind, .thunder, .whistle] + (1...5).map(SoundEffect.beeps)
20}
21
22/// Renders sound effects to mono sample buffers. Every sound fades in and out
23/// smoothly and starts and ends on silence, so there are no clicks.
24nonisolated enum SoundSynth {
25 static let sampleRate: Double = 44_100
26
27 /// Silence at each end so playback never starts or stops mid-wave.
28 private static let pad = 0.004
29
30 static func duration(_ effect: SoundEffect) -> Double {
31 Double(render(effect).count) / sampleRate
32 }
33
34 static func render(_ effect: SoundEffect) -> [Float] {
35 switch effect {
36 case .success:
37 mix([
38 Note(frequency: 523.25, start: 0, duration: 0.14),
39 Note(frequency: 659.25, start: 0.1, duration: 0.14),
40 Note(frequency: 783.99, start: 0.2, duration: 0.22),
41 ], peak: 0.6)
42 case .gentleMiss:
43 mix([
44 Note(frequency: 329.63, start: 0, duration: 0.17, harmonics: [1, 0.15]),
45 Note(frequency: 261.63, start: 0.15, duration: 0.18, harmonics: [1, 0.15]),
46 ], peak: 0.45)
47 case .roundComplete:
48 mix([
49 Note(frequency: 523.25, start: 0, duration: 0.14, gain: 2.2),
50 Note(frequency: 659.25, start: 0.12, duration: 0.14, gain: 2.2),
51 Note(frequency: 783.99, start: 0.24, duration: 0.14, gain: 2.2),
52 Note(frequency: 523.25, start: 0.4, duration: 0.7),
53 Note(frequency: 659.25, start: 0.4, duration: 0.7),
54 Note(frequency: 783.99, start: 0.4, duration: 0.7),
55 Note(frequency: 1046.5, start: 0.4, duration: 0.7),
56 ], peak: 0.6)
57 case .whistle:
58 whistle()
59 case .beeps(let count):
60 mix((0..<count).map {
61 Note(frequency: 660, start: 0.42 * Double($0), duration: 0.12, harmonics: [1, 0.2])
62 }, peak: 0.5)
63 case .moo:
64 voice(Voice(duration: 1.2,
65 pitch: [(0, 105), (0.25, 135), (0.7, 125), (1, 95)],
66 vowels: [(0, [260, 600, 2200]), (0.3, [480, 850, 2300]),
67 (0.75, [380, 700, 2200]), (1, [260, 550, 2200])],
68 bandwidth: 110, rolloff: 1.3, vibrato: (5, 0.01),
69 attack: 0.12, release: 0.25),
70 peak: 0.75)
71 case .meow:
72 voice(Voice(duration: 0.7,
73 pitch: [(0, 480), (0.4, 720), (1, 430)],
74 vowels: [(0, [300, 2300, 3000]), (0.35, [850, 1600, 2800]), (1, [400, 900, 2600])],
75 bandwidth: 300, rolloff: 0.6, attack: 0.04, release: 0.15),
76 peak: 0.35)
77 case .baa:
78 voice(Voice(duration: 0.8,
79 pitch: [(0, 360), (0.15, 330), (1, 300)],
80 vowels: [(0, [350, 1200, 2500]), (0.12, [750, 1650, 2600]), (1, [700, 1500, 2500])],
81 bandwidth: 250, rolloff: 0.5, vibrato: (7, 0.04), tremolo: (7, 0.5),
82 attack: 0.03, release: 0.2),
83 peak: 0.55)
84 case .quack:
85 repeated(at: [0, 0.28], Voice(duration: 0.18,
86 pitch: [(0, 240), (1, 190)],
87 vowels: [(0, [1000, 2500, 3200]), (1, [850, 2000, 3000])],
88 bandwidth: 200, rolloff: 0.2, attack: 0.012, release: 0.05, noise: 0.1),
89 peak: 0.5)
90 case .oink:
91 repeated(at: [0, 0.3], Voice(duration: 0.2,
92 pitch: [(0, 150), (1, 110)],
93 vowels: [(0, [400, 1100, 2400]), (1, [350, 900, 2300])],
94 bandwidth: 150, rolloff: 0.4, tremolo: (30, 0.6),
95 attack: 0.015, release: 0.06, noise: 0.3),
96 peak: 0.75)
97 case .woof:
98 repeated(at: [0, 0.32], Voice(duration: 0.18,
99 pitch: [(0, 320), (0.3, 260), (1, 170)],
100 vowels: [(0, [350, 800, 2300]), (0.25, [650, 1100, 2500]), (1, [500, 900, 2400])],
101 bandwidth: 220, rolloff: 0.4, attack: 0.01, release: 0.07, noise: 0.25),
102 peak: 0.55)
103 case .tweet:
104 tweet()
105 case .rain:
106 rain()
107 case .wind:
108 wind()
109 case .thunder:
110 thunder()
111 }
112 }
113
114 // MARK: - Notes
115
116 private struct Note {
117 let frequency: Double
118 let start: Double
119 let duration: Double
120 var harmonics: [Double] = [1, 0.3, 0.1]
121 var gain: Double = 1
122 }
123
124 private static func mix(_ notes: [Note], peak: Float) -> [Float] {
125 let end = notes.map { $0.start + $0.duration }.max()!
126 var out = [Float](repeating: 0, count: Int((end + 2 * pad) * sampleRate))
127 for note in notes {
128 let offset = Int((note.start + pad) * sampleRate)
129 let count = Int(note.duration * sampleRate)
130 for i in 0..<count {
131 let t = Double(i) / sampleRate
132 var v = 0.0
133 for (n, amp) in note.harmonics.enumerated() {
134 v += amp * sin(2 * .pi * note.frequency * Double(n + 1) * t)
135 }
136 out[offset + i] += Float(note.gain * v * envelope(t, duration: note.duration))
137 }
138 }
139 return normalized(out, peak: peak)
140 }
141
142 /// Smooth attack, gentle exponential decay, smooth release to zero.
143 private static func envelope(_ t: Double, duration: Double) -> Double {
144 let attack = 0.01, release = 0.03
145 return fade(t, duration: duration, attack: attack, release: release) * exp(-3 * t / max(duration, 0.1))
146 }
147
148 // MARK: - Voices
149
150 /// A pitched source whose harmonics are shaped by moving formant peaks,
151 /// the way a mouth shapes a vowel.
152 private struct Voice {
153 var duration: Double
154 /// (fraction of duration, Hz) breakpoints.
155 var pitch: [(Double, Double)]
156 /// (fraction of duration, formant Hz) breakpoints. Empty means no shaping.
157 var vowels: [(Double, [Double])] = []
158 var bandwidth: Double = 150
159 /// Harmonic n is weighted by 1 / n^rolloff.
160 var rolloff: Double = 0.5
161 var maxHarmonics = 60
162 /// (rate Hz, depth as a fraction of pitch).
163 var vibrato: (Double, Double) = (0, 0)
164 /// (rate Hz, depth as a fraction of level).
165 var tremolo: (Double, Double) = (0, 0)
166 var attack = 0.03
167 var release = 0.08
168 var noise = 0.0
169 }
170
171 /// Two steady, nearly pure tones a major third apart with a little
172 /// vibrato and breath, like a toy train whistle.
173 private static func whistle() -> [Float] {
174 let tones = [600.0, 755.0].enumerated().map { i, f in
175 voiceSamples(Voice(duration: 0.9, pitch: [(0, f * 0.97), (0.15, f), (1, f)],
176 rolloff: 2, maxHarmonics: 6, vibrato: (5.5, 0.006),
177 attack: 0.08, release: 0.2, noise: 0.03),
178 seed: UInt64(10 + i))
179 }
180 let count = min(tones[0].count, tones[1].count)
181 return normalized(padded((0..<count).map { tones[0][$0] + tones[1][$0] }), peak: 0.4)
182 }
183
184 private static func voice(_ v: Voice, peak: Float) -> [Float] {
185 normalized(padded(voiceSamples(v, seed: 1)), peak: peak)
186 }
187
188 private static func repeated(at starts: [Double], _ v: Voice, peak: Float) -> [Float] {
189 let one = voiceSamples(v, seed: 1)
190 let end = starts.max()! + v.duration
191 var out = [Float](repeating: 0, count: Int(end * sampleRate) + 1)
192 for start in starts {
193 let offset = Int(start * sampleRate)
194 for (i, s) in one.enumerated() where offset + i < out.count { out[offset + i] += s }
195 }
196 return normalized(padded(out), peak: peak)
197 }
198
199 private static func voiceSamples(_ v: Voice, seed: UInt64) -> [Float] {
200 let count = Int(v.duration * sampleRate)
201 var out = [Float](repeating: 0, count: count)
202 var noise = Noise(seed: seed)
203 var phase = 0.0
204 var gains = [Double]()
205 var smoothNoise = 0.0
206 let nyquistGuard = 7_000.0
207 for i in 0..<count {
208 let t = Double(i) / sampleRate
209 let u = t / v.duration
210 let f0 = interpolate(v.pitch, u) * (1 + v.vibrato.1 * sin(2 * .pi * v.vibrato.0 * t))
211 phase += 2 * .pi * f0 / sampleRate
212 let harmonics = min(v.maxHarmonics, Int(nyquistGuard / f0))
213 if i % 32 == 0 {
214 let formants = v.vowels.isEmpty ? [] : interpolate(v.vowels, u)
215 gains = (1...max(harmonics, 1)).map { n in
216 let f = Double(n) * f0
217 var g = formants.isEmpty ? 1 : 0.02
218 for (k, formant) in formants.enumerated() {
219 let d = (f - formant) / v.bandwidth
220 g += pow(0.55, Double(k)) * exp(-d * d)
221 }
222 return g / pow(Double(n), v.rolloff)
223 }
224 }
225 var s = 0.0
226 for n in 0..<min(harmonics, gains.count) {
227 s += gains[n] * sin(Double(n + 1) * phase)
228 }
229 smoothNoise += 0.3 * (noise.next() - smoothNoise)
230 s += v.noise * 4 * smoothNoise
231 let level = 1 - v.tremolo.1 * (0.5 + 0.5 * sin(2 * .pi * v.tremolo.0 * t))
232 out[i] = Float(s * level * fade(t, duration: v.duration, attack: v.attack, release: v.release))
233 }
234 return out
235 }
236
237 /// Three rising chirps, then a short warble.
238 private static func tweet() -> [Float] {
239 let chirp = Voice(duration: 0.09, pitch: [(0, 2500), (1, 4200)], rolloff: 2,
240 maxHarmonics: 2, attack: 0.01, release: 0.03)
241 let warble = Voice(duration: 0.25, pitch: [(0, 3800), (0.5, 3200), (1, 3600)], rolloff: 2,
242 maxHarmonics: 2, vibrato: (25, 0.05), attack: 0.02, release: 0.06)
243 var out = [Float](repeating: 0, count: Int(0.68 * sampleRate))
244 for (start, v) in [(0.0, chirp), (0.13, chirp), (0.26, chirp), (0.42, warble)] {
245 let offset = Int(start * sampleRate)
246 for (i, s) in voiceSamples(v, seed: 1).enumerated() where offset + i < out.count {
247 out[offset + i] += s
248 }
249 }
250 return normalized(padded(out), peak: 0.3)
251 }
252
253 // MARK: - Weather
254
255 /// Soft high hiss with scattered droplets.
256 private static func rain() -> [Float] {
257 let duration = 2.0
258 let count = Int(duration * sampleRate)
259 var noise = Noise(seed: 7)
260 var out = [Float](repeating: 0, count: count)
261 var low = 0.0, body = 0.0
262 for i in 0..<count {
263 low += 0.3 * (noise.next() - low) // soften the top end
264 body += 0.2 * (low - body) // what is left below ~1.4 kHz
265 out[i] = Float(0.5 * (low - body))
266 }
267 for _ in 0..<70 {
268 let start = Int(noise.unit() * (duration - 0.05) * sampleRate)
269 let frequency = 1500 + noise.unit() * 3000
270 let amplitude = 0.15 + noise.unit() * 0.3
271 let length = Int(0.018 * sampleRate)
272 for j in 0..<length where start + j < count {
273 let t = Double(j) / sampleRate
274 let shape = fade(t, duration: 0.018, attack: 0.002, release: 0.006) * exp(-t / 0.005)
275 out[start + j] += Float(amplitude * shape * sin(2 * .pi * frequency * t))
276 }
277 }
278 return finish(out, duration: duration, attack: 0.3, release: 0.4, peak: 0.45)
279 }
280
281 /// Band-passed noise whose center drifts, with a slow swell.
282 private static func wind() -> [Float] {
283 let duration = 2.2
284 let count = Int(duration * sampleRate)
285 var noise = Noise(seed: 11)
286 var out = [Float](repeating: 0, count: count)
287 var y1 = 0.0, y2 = 0.0
288 for i in 0..<count {
289 let t = Double(i) / sampleRate
290 let u = t / duration
291 let center = interpolate([(0, 250), (0.45, 700), (1, 350)], u)
292 let r = 0.995
293 let theta = 2 * .pi * center / sampleRate
294 let y = noise.next() * (1 - r) + 2 * r * cos(theta) * y1 - r * r * y2
295 y2 = y1
296 y1 = y
297 let swell = pow(sin(.pi * u), 1.5) * (1 + 0.3 * sin(2 * .pi * 0.8 * t))
298 out[i] = Float(y * swell)
299 }
300 return finish(out, duration: duration, attack: 0.2, release: 0.4, peak: 0.45)
301 }
302
303 /// Low rolling rumble with a soft start and two swells. No sharp crack.
304 private static func thunder() -> [Float] {
305 let duration = 2.4
306 let count = Int(duration * sampleRate)
307 var noise = Noise(seed: 13)
308 var out = [Float](repeating: 0, count: count)
309 var a = 0.0, b = 0.0
310 for i in 0..<count {
311 let t = Double(i) / sampleRate
312 a += 0.06 * (noise.next() - a)
313 b += 0.06 * (a - b)
314 let swells = exp(-pow((t - 0.35) / 0.3, 2)) + 0.7 * exp(-pow((t - 1.2) / 0.45, 2))
315 out[i] = Float(b * swells)
316 }
317 return finish(dcBlocked(out), duration: duration, attack: 0.15, release: 0.5, peak: 0.55)
318 }
319
320 // MARK: - Helpers
321
322 /// Seeded white noise in -1...1 (SplitMix64), so sounds render the same every time.
323 private struct Noise {
324 var state: UInt64
325 init(seed: UInt64) { state = seed }
326 mutating func unit() -> Double {
327 state &+= 0x9E37_79B9_7F4A_7C15
328 var z = state
329 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
330 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
331 return Double((z ^ (z >> 31)) >> 11) / Double(1 << 53)
332 }
333 mutating func next() -> Double { 2 * unit() - 1 }
334 }
335
336 /// sin² fade-in over `attack` and fade-out over `release`.
337 private static func fade(_ t: Double, duration: Double, attack: Double, release: Double) -> Double {
338 let rise = t < attack ? pow(sin(.pi / 2 * t / attack), 2) : 1
339 let fall = t > duration - release ? pow(sin(.pi / 2 * max(0, duration - t) / release), 2) : 1
340 return rise * fall
341 }
342
343 private static func interpolate(_ points: [(Double, Double)], _ u: Double) -> Double {
344 guard let upper = points.firstIndex(where: { $0.0 >= u }), upper > 0 else {
345 return u <= points[0].0 ? points[0].1 : points[points.count - 1].1
346 }
347 let (u0, v0) = points[upper - 1], (u1, v1) = points[upper]
348 return v0 + (v1 - v0) * (u - u0) / (u1 - u0)
349 }
350
351 private static func interpolate(_ points: [(Double, [Double])], _ u: Double) -> [Double] {
352 (0..<points[0].1.count).map { k in interpolate(points.map { ($0.0, $0.1[k]) }, u) }
353 }
354
355 private static func dcBlocked(_ s: [Float]) -> [Float] {
356 var out = s
357 var previousIn: Float = 0, previousOut: Float = 0
358 for i in s.indices {
359 previousOut = s[i] - previousIn + 0.999 * previousOut
360 previousIn = s[i]
361 out[i] = previousOut
362 }
363 return out
364 }
365
366 /// Fades, removes any remaining offset, pads, and normalizes.
367 private static func finish(_ s: [Float], duration: Double, attack: Double, release: Double, peak: Float) -> [Float] {
368 let mean = s.reduce(0, +) / Float(s.count)
369 let shaped = s.enumerated().map { i, x in
370 (x - mean) * Float(fade(Double(i) / sampleRate, duration: duration, attack: attack, release: release))
371 }
372 return normalized(padded(shaped), peak: peak)
373 }
374
375 private static func padded(_ s: [Float]) -> [Float] {
376 let silence = [Float](repeating: 0, count: Int(pad * sampleRate))
377 return silence + s + silence
378 }
379
380 private static func normalized(_ s: [Float], peak: Float) -> [Float] {
381 let maxAbs = s.map(abs).max() ?? 1
382 guard maxAbs > 0 else { return s }
383 return s.map { $0 / maxAbs * peak }
384 }
385}