// // SoundSynth.swift // DayByDay // import Foundation nonisolated enum SoundEffect: Hashable, CaseIterable, Sendable { case success, gentleMiss, roundComplete case moo, quack, baa, oink, meow, woof, tweet case rain, wind, thunder /// Two-tone train whistle, for a finished week train. case whistle /// That many short beeps, for counting. case beeps(Int) static let allCases: [SoundEffect] = [.success, .gentleMiss, .roundComplete, .moo, .quack, .baa, .oink, .meow, .woof, .tweet, .rain, .wind, .thunder, .whistle] + (1...5).map(SoundEffect.beeps) } /// Renders sound effects to mono sample buffers. Every sound fades in and out /// smoothly and starts and ends on silence, so there are no clicks. nonisolated enum SoundSynth { static let sampleRate: Double = 44_100 /// Silence at each end so playback never starts or stops mid-wave. private static let pad = 0.004 static func duration(_ effect: SoundEffect) -> Double { Double(render(effect).count) / sampleRate } static func render(_ effect: SoundEffect) -> [Float] { switch effect { case .success: mix([ Note(frequency: 523.25, start: 0, duration: 0.14), Note(frequency: 659.25, start: 0.1, duration: 0.14), Note(frequency: 783.99, start: 0.2, duration: 0.22), ], peak: 0.6) case .gentleMiss: mix([ Note(frequency: 329.63, start: 0, duration: 0.17, harmonics: [1, 0.15]), Note(frequency: 261.63, start: 0.15, duration: 0.18, harmonics: [1, 0.15]), ], peak: 0.45) case .roundComplete: mix([ Note(frequency: 523.25, start: 0, duration: 0.14, gain: 2.2), Note(frequency: 659.25, start: 0.12, duration: 0.14, gain: 2.2), Note(frequency: 783.99, start: 0.24, duration: 0.14, gain: 2.2), Note(frequency: 523.25, start: 0.4, duration: 0.7), Note(frequency: 659.25, start: 0.4, duration: 0.7), Note(frequency: 783.99, start: 0.4, duration: 0.7), Note(frequency: 1046.5, start: 0.4, duration: 0.7), ], peak: 0.6) case .whistle: whistle() case .beeps(let count): mix((0.. [Float] { let end = notes.map { $0.start + $0.duration }.max()! var out = [Float](repeating: 0, count: Int((end + 2 * pad) * sampleRate)) for note in notes { let offset = Int((note.start + pad) * sampleRate) let count = Int(note.duration * sampleRate) for i in 0.. Double { let attack = 0.01, release = 0.03 return fade(t, duration: duration, attack: attack, release: release) * exp(-3 * t / max(duration, 0.1)) } // MARK: - Voices /// A pitched source whose harmonics are shaped by moving formant peaks, /// the way a mouth shapes a vowel. private struct Voice { var duration: Double /// (fraction of duration, Hz) breakpoints. var pitch: [(Double, Double)] /// (fraction of duration, formant Hz) breakpoints. Empty means no shaping. var vowels: [(Double, [Double])] = [] var bandwidth: Double = 150 /// Harmonic n is weighted by 1 / n^rolloff. var rolloff: Double = 0.5 var maxHarmonics = 60 /// (rate Hz, depth as a fraction of pitch). var vibrato: (Double, Double) = (0, 0) /// (rate Hz, depth as a fraction of level). var tremolo: (Double, Double) = (0, 0) var attack = 0.03 var release = 0.08 var noise = 0.0 } /// Two steady, nearly pure tones a major third apart with a little /// vibrato and breath, like a toy train whistle. private static func whistle() -> [Float] { let tones = [600.0, 755.0].enumerated().map { i, f in voiceSamples(Voice(duration: 0.9, pitch: [(0, f * 0.97), (0.15, f), (1, f)], rolloff: 2, maxHarmonics: 6, vibrato: (5.5, 0.006), attack: 0.08, release: 0.2, noise: 0.03), seed: UInt64(10 + i)) } let count = min(tones[0].count, tones[1].count) return normalized(padded((0.. [Float] { normalized(padded(voiceSamples(v, seed: 1)), peak: peak) } private static func repeated(at starts: [Double], _ v: Voice, peak: Float) -> [Float] { let one = voiceSamples(v, seed: 1) let end = starts.max()! + v.duration var out = [Float](repeating: 0, count: Int(end * sampleRate) + 1) for start in starts { let offset = Int(start * sampleRate) for (i, s) in one.enumerated() where offset + i < out.count { out[offset + i] += s } } return normalized(padded(out), peak: peak) } private static func voiceSamples(_ v: Voice, seed: UInt64) -> [Float] { let count = Int(v.duration * sampleRate) var out = [Float](repeating: 0, count: count) var noise = Noise(seed: seed) var phase = 0.0 var gains = [Double]() var smoothNoise = 0.0 let nyquistGuard = 7_000.0 for i in 0.. [Float] { let chirp = Voice(duration: 0.09, pitch: [(0, 2500), (1, 4200)], rolloff: 2, maxHarmonics: 2, attack: 0.01, release: 0.03) let warble = Voice(duration: 0.25, pitch: [(0, 3800), (0.5, 3200), (1, 3600)], rolloff: 2, maxHarmonics: 2, vibrato: (25, 0.05), attack: 0.02, release: 0.06) var out = [Float](repeating: 0, count: Int(0.68 * sampleRate)) for (start, v) in [(0.0, chirp), (0.13, chirp), (0.26, chirp), (0.42, warble)] { let offset = Int(start * sampleRate) for (i, s) in voiceSamples(v, seed: 1).enumerated() where offset + i < out.count { out[offset + i] += s } } return normalized(padded(out), peak: 0.3) } // MARK: - Weather /// Soft high hiss with scattered droplets. private static func rain() -> [Float] { let duration = 2.0 let count = Int(duration * sampleRate) var noise = Noise(seed: 7) var out = [Float](repeating: 0, count: count) var low = 0.0, body = 0.0 for i in 0.. [Float] { let duration = 2.2 let count = Int(duration * sampleRate) var noise = Noise(seed: 11) var out = [Float](repeating: 0, count: count) var y1 = 0.0, y2 = 0.0 for i in 0.. [Float] { let duration = 2.4 let count = Int(duration * sampleRate) var noise = Noise(seed: 13) var out = [Float](repeating: 0, count: count) var a = 0.0, b = 0.0 for i in 0.. Double { state &+= 0x9E37_79B9_7F4A_7C15 var z = state z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB return Double((z ^ (z >> 31)) >> 11) / Double(1 << 53) } mutating func next() -> Double { 2 * unit() - 1 } } /// sin² fade-in over `attack` and fade-out over `release`. private static func fade(_ t: Double, duration: Double, attack: Double, release: Double) -> Double { let rise = t < attack ? pow(sin(.pi / 2 * t / attack), 2) : 1 let fall = t > duration - release ? pow(sin(.pi / 2 * max(0, duration - t) / release), 2) : 1 return rise * fall } private static func interpolate(_ points: [(Double, Double)], _ u: Double) -> Double { guard let upper = points.firstIndex(where: { $0.0 >= u }), upper > 0 else { return u <= points[0].0 ? points[0].1 : points[points.count - 1].1 } let (u0, v0) = points[upper - 1], (u1, v1) = points[upper] return v0 + (v1 - v0) * (u - u0) / (u1 - u0) } private static func interpolate(_ points: [(Double, [Double])], _ u: Double) -> [Double] { (0.. [Float] { var out = s var previousIn: Float = 0, previousOut: Float = 0 for i in s.indices { previousOut = s[i] - previousIn + 0.999 * previousOut previousIn = s[i] out[i] = previousOut } return out } /// Fades, removes any remaining offset, pads, and normalizes. private static func finish(_ s: [Float], duration: Double, attack: Double, release: Double, peak: Float) -> [Float] { let mean = s.reduce(0, +) / Float(s.count) let shaped = s.enumerated().map { i, x in (x - mean) * Float(fade(Double(i) / sampleRate, duration: duration, attack: attack, release: release)) } return normalized(padded(shaped), peak: peak) } private static func padded(_ s: [Float]) -> [Float] { let silence = [Float](repeating: 0, count: Int(pad * sampleRate)) return silence + s + silence } private static func normalized(_ s: [Float], peak: Float) -> [Float] { let maxAbs = s.map(abs).max() ?? 1 guard maxAbs > 0 else { return s } return s.map { $0 / maxAbs * peak } } }