Files
Lyrebird/docs/learning-swift/01-hello-world.md
T
josh abc64df4d7 v1.4.1 release: Learning Swift for Lyrebird intro guide
Documentation-only release. Adds docs/learning-swift/ — a four-part
introduction to Swift for Lyrebird users coming from SuperCollider,
Max/MSP, Csound, etc. (Hello World, Swift basics & best practices,
types & functional programming, Xcode/packages/debugging). Linked from
README.md and LYREBIRD_START_HERE.md. See RELEASES.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 12:10:00 -07:00

8.6 KiB

1 · Hello, World

The programmer's tradition is a program that prints Hello, World. Lyrebird's tradition is a program that makes a tone. We'll do both — the print first (to prove your toolchain works), then the sound.

By the end of this page you will have written, built, and run a Swift program that plays a 440 Hz sine wave, and you'll understand every line.


Part 0 — Prove Swift works

Open Terminal (Applications → Utilities → Terminal). Check you have a Swift toolchain:

swift --version

You should see something like Apple Swift version 6.0. If you get "command not found", install Xcode from the Mac App Store, launch it once, and let it install command-line tools. (Guide 4 covers Xcode in depth.)

Now the classic:

echo 'print("Hello, World")' > hello.swift
swift hello.swift

Swift can run a single file like a script. If you see Hello, World, your toolchain is alive. That's the smallest possible Swift program:

print("Hello, World")
  • print(...) is a function that writes text to the console.
  • "Hello, World" is a String — text in double quotes.
  • No main, no boilerplate, no semicolons required. Swift keeps simple things simple.

Part 1 — The shape of a Lyrebird program

A Lyrebird program is a normal Swift program that uses the Lyrebird library. Here is the entire "hello tone", which you'll build up in Part 2:

import Foundation
import LyrebirdSynth

// The engine owns Core Audio and runs the audio graph.
let engine: SynthesisEngine = SynthesisEngine(
    blockSize: 512,
    sampleRate: 48000,
    numOutputChannels: 2,
    numInputChannels: 0,
    driver: CoreAudioDriver()
)

// A synthesizer describes the sound.
final class SineTone: SynthesizerBase {
    override func build() {
        let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.2)
        let panned: Pan2 = Pan2(input: sine, pan: 0.0)
        output(bus: 0, source: panned)
    }
}

do {
    try engine.start()          // open the audio device
    try engine.add(SineTone())  // start sounding
    print("Playing 440 Hz for 3 seconds…")
    Thread.sleep(forTimeInterval: 3.0)
    engine.stop()               // close the device
    print("Done.")
} catch {
    print("Something went wrong: \(error)")
}

Run that and you hear a sine tone for three seconds. Now let's read it.


Part 2 — Reading it line by line

The imports

import Foundation
import LyrebirdSynth

import pulls in a module — a bundle of code someone else wrote. Foundation is Apple's standard utility library (it's where Thread.sleep lives). LyrebirdSynth is Lyrebird itself.

The naming quirk: the Swift Package product is named Lyrebird, but the module you import is LyrebirdSynth. When you set up a project (guide 4) you'll add a dependency on Lyrebird — then write import LyrebirdSynth. Right for both, even though they don't match.

Creating the engine

let engine: SynthesisEngine = SynthesisEngine(
    blockSize: 512,
    sampleRate: 48000,
    numOutputChannels: 2,
    numInputChannels: 0,
    driver: CoreAudioDriver()
)
  • let engine: SynthesisEngine = ... declares a constant named engine, and the : SynthesisEngine is a type annotation — it states the type explicitly. let means "this name won't be reassigned." (Swift also has var for values that change — guide 2.)
  • Every example in this series annotates the type, even though Swift can infer it. It documents the code for the reader and, in a large project, makes Swift and Xcode compile faster — the compiler doesn't have to work out each type. Guide 2 explains this properly; for now, read name: Type = value as "a constant of this type." (Swift also has var for values that change — guide 2.)
  • SynthesisEngine(...) constructs an engine. The words before each colon (blockSize:, sampleRate:, …) are argument labels — Swift names its arguments, which makes call sites read like sentences. You can't reorder or omit them.
  • blockSize: 512 — the engine processes audio 512 samples at a time. (Lyrebird caps this at 512.)
  • sampleRate: 48000 — 48,000 samples per second.
  • numOutputChannels: 2 — stereo out. numInputChannels: 0 — no microphone input.
  • driver: CoreAudioDriver() — talk to the Mac's audio hardware. (iOS uses a different driver; guide 4.)

Describing the sound

final class SineTone: SynthesizerBase {
    override func build() {
        let sine: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.2)
        let panned: Pan2 = Pan2(input: sine, pan: 0.0)
        output(bus: 0, source: panned)
    }
}
  • final class SineTone: SynthesizerBase defines a new type called SineTone that inherits from SynthesizerBase. The colon means "is a." Everything a synthesizer needs is in SynthesizerBase; you fill in the blanks. final means "no one will subclass this further" (good default; guide 2).
  • override func build() — SynthesizerBase has an empty build() method; you override it to supply your graph. Lyrebird calls build() for you when the synth is added.
  • OscSin.Audio(freq: 440.0, mul: 0.2) — an audio-rate sine oscillator at 440 Hz, with output multiplied by 0.2 so it isn't harsh. A raw sine at full scale is loud; mul: 0.2 scales amplitude to 20%.
  • Pan2(input: sine, pan: 0.0) — takes a mono signal and places it in the stereo field. pan: 0.0 is dead center; -1 is hard left, +1 hard right.
  • output(bus: 0, source: panned) — send the panned signal to output bus 0. Pan2 produces two channels, so this fills both left and right. output(...) is a helper SynthesizerBase gives you.

Notice the data flow: sine feeds panned feeds output. Each generator is a node; wiring them by passing one as another's input: builds a graph. That's the core idea of Lyrebird.

Running it

do {
    try engine.start()
    try engine.add(SineTone())
    print("Playing 440 Hz for 3 seconds…")
    Thread.sleep(forTimeInterval: 3.0)
    engine.stop()
    print("Done.")
} catch {
    print("Something went wrong: \(error)")
}
  • do { … } catch { … } is Swift's error handling. Some operations can fail; those are marked try. If a try fails, control jumps to catch, where error describes what happened. (Guide 2 covers this properly.)
  • try engine.start() opens the audio device. It can fail (device busy, no output) — hence try.
  • try engine.add(SineTone()) constructs a fresh SineTone and hands it to the engine. It starts sounding immediately. add can also fail (hence try), for example if you add the same instance twice.
  • Thread.sleep(forTimeInterval: 3.0) pauses the program for 3 seconds. Without this, the program would reach the end and exit instantly — you'd hear nothing. Audio runs on its own thread; the main program just needs to stay alive.
  • engine.stop() closes the device cleanly. (Not try — stopping doesn't fail.)
  • \(error) inside a string is string interpolation: it drops the value of error into the text.

Part 3 — Make it yours

Change one thing at a time and re-run. This is the fastest way to build intuition:

  • Pitch: freq: 440.0 → freq: 220.0 (an octave down) or freq: 660.0 (a fifth up).
  • Loudness: mul: 0.2 → mul: 0.4. Careful with headphones.
  • Position: pan: 0.0 → pan: -1.0 (hard left).
  • Duration: forTimeInterval: 3.0 → 10.0.
  • A different wave: OscSin.Audio → OscSawtooth.Audio (bright, buzzy) or OscSquare.Audio (hollow). Same freq:/mul: arguments.

Try two oscillators at once for a chord — a taste of what guide 3 makes systematic:

override func build() {
    let a: OscSin.Audio = OscSin.Audio(freq: 440.0, mul: 0.15)   // A4
    let e: OscSin.Audio = OscSin.Audio(freq: 660.0, mul: 0.15)   // E5
    let mix: BinaryOpGenerator = a + e                           // generators add with +
    output(bus: 0, source: Pan2(input: mix, pan: 0.0))
}

a + e sums two signals — Lyrebird overloads + so audio math reads like arithmetic. More of that in guide 3.


What you learned

  • A Swift program can be as small as one print, or a full Lyrebird patch — same language, same rules.
  • import, let with a type annotation (let x: Type = …), argument labels, class/override, and do/try/catch — you've now seen Swift's most common building blocks in context.
  • Lyrebird's shape: engine → synthesizer → generator graph → output bus.

Next: Swift Basics & Best Practices — the same building blocks, slowed down and explained properly, so you can write your own from scratch.