Files
Lyrebird/Demos/LyrebirdiOSDemo/LyrebirdiOSDemo/UI/BinDelayController.swift
T

76 lines
2.2 KiB
Swift

// BinDelayController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Observation
import LyrebirdSynth
/// Controller for the spectral-bin-delay demo view.
///
/// Unlike `NoteController`, the synthesizer is created lazily when the user
/// first taps "Start Synthesizer" — this is necessary because
/// `SpectralBinDelayUI.init(sampleRate:)` requires the engine's committed
/// sample rate, which is only valid after `engine.start()` returns.
@MainActor
@Observable
final class BinDelayController {
let engine: SynthesisEngine
let scopeCapture: ScopeCapture
private(set) var engineRunning: Bool = false
private(set) var isPlaying: Bool = false
/// The live synthesizer instance. `nil` until first "Start Synthesizer" tap.
private(set) var synth: SpectralBinDelayUI?
init(engine: SynthesisEngine, scopeCapture: ScopeCapture) {
self.engine = engine
self.scopeCapture = scopeCapture
}
func toggleEngine() {
if engineRunning {
if isPlaying, let s = synth {
engine.remove(s)
isPlaying = false
}
engine.stop()
engineRunning = false
} else {
do {
try engine.start()
engineRunning = true
} catch {
print("Engine failed to start: \(error)")
}
}
}
func toggle() {
if isPlaying {
if let s = synth {
engine.remove(s)
}
isPlaying = false
} else {
guard engineRunning else { return }
// Create the synthesizer lazily so we don't put it in the node tree
// until the user requests it.
if synth == nil {
synth = SpectralBinDelayUI(sampleRate: engine.sampleRate)
}
if let s = synth {
do {
try engine.add(s)
isPlaying = true
} catch {
print("[Lyrebird] BinDelayController.toggle add failed: \(error)")
}
}
}
}
}