Files
Lyrebird/Sources/Lyrebird/Synthesizer/ClosureSynthesizer.swift
T

59 lines
2.3 KiB
Swift

// ClosureSynthesizer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// A `SynthesizerBase` whose signal graph is supplied by a closure instead of a
// `build()` override. The escape hatch for "just play this generator graph"
// without declaring a named `Synthesizer` subclass — the fastest path from a
// bare graph to audible sound (scratchpads, demos, tests, one-off voices).
/// A `SynthesizerBase` that builds its output graph from a closure.
///
/// Skips the usual "declare a subclass, override `build()`" ceremony when all
/// you want is to hear a generator graph:
///
/// ```swift
/// try engine.add(ClosureSynthesizer { OscSin.Audio(freq: 440, mul: 0.1) })
/// try engine.add(ClosureSynthesizer(bus: 0) { Pan2(input: saw, pan: 0) })
/// ```
///
/// The closure runs inside ``build()`` — once, on the main thread, when the
/// synthesizer is added to an engine. Each instance is its own graph, so
/// **construct the generators inside the closure** rather than handing it
/// generator instances shared with another synthesizer (the same
/// graph-copy-per-instance rule that applies to any `SynthesizerBase`).
///
/// A multi-channel source (e.g. a `Pan2`) fans out across consecutive buses
/// starting at `bus`, exactly as ``SynthesizerBase/output(bus:source:)`` does.
///
/// - Parameters:
/// - bus: The output bus the graph is written to. A multi-channel source
/// continues into the following buses. Defaults to `0`.
/// - make: Builds and returns the output graph. Called once per instance,
/// inside `build()`.
public final class ClosureSynthesizer: SynthesizerBase {
private let outputBus: any ValidBus
private let make: () -> any ValidGeneratorInput
/// - Parameters:
/// - bus: The output bus the graph is written to. A multi-channel source
/// continues into the following buses. Defaults to `0`.
/// - make: Builds and returns the output graph. Called once per instance,
/// inside `build()`. Construct the generators inside the closure.
public init(
bus: any ValidBus = 0,
_ make: @escaping () -> any ValidGeneratorInput
) {
self.outputBus = bus
self.make = make
super.init()
}
public override func build() {
output(bus: outputBus, source: make())
}
}