Files
Lyrebird/Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdTask.xctemplate/___FILEBASENAME___.swift
T

67 lines
2.2 KiB
Swift

//___FILEHEADER___
import Foundation
import LyrebirdSynth
// MARK: - ___FILEBASENAMEASIDENTIFIER___
/// Factory for a `LyrebirdTask` that runs a scheduled-event loop on its own
/// background thread.
///
/// The task body receives a `LyrebirdRoutineContext` providing:
/// - `add(_:)` — attach a Synthesizer to the engine
/// - `wait(seconds:)` — sleep, respecting `pause()` / `stop()`
/// - `wait(beats:tempo:)` — tempo-aware sleep
///
/// Throwing `LyrebirdRoutineError.stopped` (raised internally by `wait` when
/// `stop()` is called) exits cleanly.
///
/// ## Usage
/// ```swift
/// let task = make___FILEBASENAMEASIDENTIFIER___()
/// task.start(engine: engine)
///
/// task.pause() // freeze event stream
/// task.resume() // continue from where it stopped
/// task.stop() // exit the loop cleanly
/// ```
public func make___FILEBASENAMEASIDENTIFIER___() -> LyrebirdTask {
LyrebirdTask { ctx in
// Replace this with whatever event sequence the task should run.
// The example below schedules one short Synthesizer every 250 ms
// until `stop()` is called.
while true {
// SynthesizerBase subclasses are @MainActor-isolated; construct on the
// main thread synchronously, then hand the instance to ctx.add which
// dispatches the engine.add to main via DispatchQueue.main.async.
let note: ExampleNote = DispatchQueue.main.sync {
MainActor.assumeIsolated { ExampleNote() }
}
ctx.add(note)
try ctx.wait(seconds: 0.25)
}
}
}
// MARK: - Example Synthesizer used by the task
/// Minimal Synthesizer scheduled by `make___FILEBASENAMEASIDENTIFIER___`.
/// Replace with your own Synthesizer type and remove this stub.
private final class ExampleNote: SynthesizerBase {
@LiveParam var frequency: Double = 440.0
override func build() {
let env = EnvelopeGen.Audio(
envelope: Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.005, 0.2],
curves: [.lin, .exponential]
),
doneAction: .freeNode
)
let osc = OscSin.Audio(freq: $frequency)
output(bus: 0, source: osc * env * 0.2)
}
}