krz/daybyday

iOS learning games for young children: days, months, seasons, numbers, letters, animals and more. education ios kids swift https://krz.sh/apps/daybyday/

DayByDay/Sound/SoundEngine.swift

062549ad26607ce9e973ed2a9a7ef6f853885f83
daybyday/DayByDay/Sound/SoundEngine.swift history · blame · raw

67 lines · 2610 bytes

6 symbols in this file
 1//
 2//  SoundEngine.swift
 3//  DayByDay
 4//
 5
 6import AVFoundation
 7
 8/// Plays synthesized sound effects. Each effect is rendered and given its
 9/// own player node the first time it plays. Separate players let effects
10/// overlap instead of cutting each other off mid-wave (which clicks). A
11/// repeat of an effect that is still playing is skipped for the same reason.
12final class SoundEngine {
13    static let shared = SoundEngine()
14
15    private let engine = AVAudioEngine()
16    private let format = AVAudioFormat(standardFormatWithSampleRate: SoundSynth.sampleRate, channels: 1)!
17    private var buffers: [SoundEffect: AVAudioPCMBuffer] = [:]
18    private var players: [SoundEffect: AVAudioPlayerNode] = [:]
19    private var busyUntil: [SoundEffect: Date] = [:]
20
21    private init() {}
22
23    func play(_ effect: SoundEffect) {
24        let buffer = buffer(for: effect)
25        let player = player(for: effect)
26        let now = Date()
27        if let busy = busyUntil[effect], busy > now { return }
28        if !engine.isRunning {
29            try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
30            try? AVAudioSession.sharedInstance().setActive(true)
31            try? engine.start()
32        }
33        busyUntil[effect] = now.addingTimeInterval(duration(effect))
34        player.scheduleBuffer(buffer, at: nil)
35        if !player.isPlaying { player.play() }
36    }
37
38    /// Time until `effect` finishes playing; zero when it is not playing.
39    func remaining(_ effect: SoundEffect) -> TimeInterval {
40        max(0, busyUntil[effect]?.timeIntervalSinceNow ?? 0)
41    }
42
43    func duration(_ effect: SoundEffect) -> TimeInterval {
44        Double(buffer(for: effect).frameLength) / SoundSynth.sampleRate
45    }
46
47    private func buffer(for effect: SoundEffect) -> AVAudioPCMBuffer {
48        if let buffer = buffers[effect] { return buffer }
49        let samples = SoundSynth.render(effect)
50        let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(samples.count))!
51        buffer.frameLength = buffer.frameCapacity
52        samples.withUnsafeBufferPointer { src in
53            buffer.floatChannelData![0].update(from: src.baseAddress!, count: samples.count)
54        }
55        buffers[effect] = buffer
56        return buffer
57    }
58
59    private func player(for effect: SoundEffect) -> AVAudioPlayerNode {
60        if let player = players[effect] { return player }
61        let player = AVAudioPlayerNode()
62        engine.attach(player)
63        engine.connect(player, to: engine.mainMixerNode, format: format)
64        players[effect] = player
65        return player
66    }
67}