// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later import AVFoundation import SwiftUI /// Android's SampleRecorder: records the microphone (or a connected audio /// interface's input) into a sample, at most 30 seconds. The audio session switches /// to play-and-record only while recording, so playback keeps its normal routing /// otherwise. Main thread. @MainActor final class SampleRecorder: ObservableObject { static let shared = SampleRecorder() @Published private(set) var isRecording = false @Published var error: String? private var recorder: AVAudioRecorder? private let file = FileManager.default.temporaryDirectory.appendingPathComponent("sample-rec.wav") func start() { guard !isRecording else { return } #if os(iOS) AVAudioSession.sharedInstance().requestRecordPermission { granted in Task { @MainActor in if granted { self.begin() } else { self.error = "Sizzle has no microphone access. Allow it in Settings › Privacy › Microphone." } } } #endif } #if os(iOS) private func begin() { let s = AVAudioSession.sharedInstance() do { try s.setCategory(.playAndRecord, options: [.defaultToSpeaker, .allowBluetoothA2DP, .mixWithOthers]) try s.setActive(true) let r = try AVAudioRecorder(url: file, settings: [ AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: 44_100, AVNumberOfChannelsKey: 1, AVLinearPCMBitDepthKey: 16, AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false, ]) guard r.record(forDuration: 30) else { throw CocoaError(.fileWriteUnknown) } recorder = r isRecording = true } catch { restoreSession() self.error = "Couldn't start recording: \(error.localizedDescription)" } } #endif /// Stop and return the take as WAV data (nil if nothing was captured). func stop() -> Data? { guard let r = recorder else { return nil } r.stop() recorder = nil isRecording = false restoreSession() defer { try? FileManager.default.removeItem(at: file) } guard let data = try? Data(contentsOf: file), data.count > 44 else { return nil } return data } private func restoreSession() { #if os(iOS) try? AVAudioSession.sharedInstance().setCategory(.playback) #endif } private static var stamp: String { "rec-\(Int(Date().timeIntervalSince1970 * 1000))" } /// Stop and put the take on Sampler [slot]'s [pad] (Android: stopRecordingInto). func stopInto(slot: Int, pad: Int) { guard let data = stop() else { return } do { try SizzleSession.shared.loadSampleData(data, name: Self.stamp, intoSlot: slot, pad: pad) } catch { self.error = error.localizedDescription } } /// Stop and make the take Grain Cloud [slot]'s source (Android: stopRecordingIntoGrain). func stopIntoGrain(slot: Int) { guard let data = stop() else { return } do { try SizzleSession.shared.loadGrainSourceData(data, name: Self.stamp, intoSlot: slot) } catch { self.error = error.localizedDescription } } }