// RecordTap.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import Foundation import LyrebirdSynth /// An internal synthesizer that taps one or more audio buses and records them to a /// WAV file via `DiskOut.Audio`. /// /// `RecordTap` reads `channelCount` consecutive audio buses starting at `firstBusIndex` /// and passes them to a `DiskOut.Audio` instance that writes to `fileURL`. It is added /// `.after(engine.mainGroup)` so it evaluates after every board and master synth has /// written their final bus values for the block. /// /// Call `diskOut?.close()` after removing the tap from the engine to flush any /// buffered frames and close the file handle. final class RecordTap: SynthesizerBase { // MARK: - Configuration /// Index of the first audio bus to record. private let firstBusIndex: Int /// Number of consecutive buses to record (and interleave into the output file). private let channelCount: Int /// Destination file URL. Created or overwritten when the `DiskOut.Audio` is initialised. private let fileURL: URL /// Sample rate written into the WAV file header. private let recordSampleRate: Double // MARK: - DiskOut handle /// The `DiskOut.Audio` generator created during `build()`. `nil` if `build()` has not /// run yet, or if `DiskOut.Audio.init` threw (error is printed to stdout). private(set) var diskOut: DiskOut.Audio? // MARK: - Init /// Creates a record tap that reads `channelCount` buses from `firstBusIndex`. /// /// - Parameters: /// - firstBusIndex: Index of the first audio bus to record. /// - channelCount: Number of consecutive audio buses to record. /// - fileURL: Output WAV file URL. Created or overwritten at build time. /// - sampleRate: Sample rate to embed in the WAV file header. init( firstBusIndex: Int, channelCount: Int, fileURL: URL, sampleRate: Double ) { self.firstBusIndex = firstBusIndex self.channelCount = channelCount self.fileURL = fileURL self.recordSampleRate = sampleRate super.init() } // MARK: - Build override func build() { let source: any ValidGeneratorInput = channelCount > 1 ? input(bus: firstBusIndex, channels: channelCount) : input(bus: firstBusIndex) do { diskOut = try DiskOut.Audio( source: source, channelCount: channelCount, url: fileURL, sampleRate: recordSampleRate, format: .wav ) // DiskOut.Audio conforms to RootRegistering and auto-registers as a synth root // when constructed inside build(). No explicit addOutputGenerator call is needed. } catch { print("[ShoeGaze] RecordTap could not open \(fileURL.lastPathComponent): \(error)") } } }