SPB Git

Repository Public

AudioEngine.swift 7.8 KB 199 lines swift

1// SP Notes Core2// File: Sources/SPNotesFeatures/Blocks/Audio/AudioEngine.swift3// Description: The audio engines of the voice note behind two small protocols (so that the view model is tested with4//              fakes): a recorder (AVAudioRecorder, AAC in an .m4a file, pause / resume, level metering, microphone5//              permission) and a player (AVAudioPlayer, seek, rate). The audio session is handled on iOS only.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import AVFoundation10import Foundation1112/// Where the audio of a voice note lives. The host app implements it over its attachment files.13public protocol AudioFileProvider: Sendable {14    /// A local file to play for an attachment (downloaded first when needed). Throw `RepositoryError.offline` when it15    /// cannot be fetched.16    func localFileURL(attachmentId: String) async throws -> URL17    /// Offline-first hand-over of a fresh recording: copy the file into the attachments directory, register it with the18    /// store (`NotesStore.addLocalAttachment`: the sync engine uploads it) and return the attachment id. Return nil19    /// (the default) to let the model upload it now through `AudioRepository.upload` — which needs the server.20    func adopt(recording: URL, pageId: String?) async throws -> String?21}2223public extension AudioFileProvider {24    func adopt(recording: URL, pageId: String?) async throws -> String? { nil }25}2627public enum AudioPermission: Sendable, Equatable {28    case undetermined, granted, denied29}3031public enum AudioEngineError: Error, Equatable, Sendable {32    case cannotRecord(String)33    case cannotPlay(String)34}3536/// A recorder: one recording at a time, to a file chosen by the caller.37@MainActor38public protocol AudioRecording: AnyObject {39    var permission: AudioPermission { get }40    /// Asks the system (shows the prompt when undetermined). True when recording is allowed.41    func requestPermission() async -> Bool42    func start(to url: URL) throws43    func pause()44    func resume()45    /// Ends the recording and closes the file; returns its duration in seconds.46    @discardableResult func stop() -> TimeInterval47    /// Seconds recorded so far (pauses excluded).48    var currentTime: TimeInterval { get }49    /// Input level 0…1 for the meter.50    var level: Double { get }51}5253/// A player of one local file.54@MainActor55public protocol AudioPlaying: AnyObject {56    /// Opens the file; returns its duration in seconds.57    @discardableResult func load(url: URL) throws -> TimeInterval58    func play()59    func pause()60    func seek(to time: TimeInterval)61    var currentTime: TimeInterval { get }62    var duration: TimeInterval { get }63    var isPlaying: Bool { get }64    /// 0.5…2.65    var rate: Double { get set }66    /// Called on the main actor when the file was played to its end.67    var onFinish: (@MainActor () -> Void)? { get set }68}6970/// The real recorder.71@MainActor72public final class SystemAudioRecorder: AudioRecording {73    private var recorder: AVAudioRecorder?7475    public init() {}7677    public var permission: AudioPermission {78        switch AVAudioApplication.shared.recordPermission {79        case .granted: return .granted80        case .denied: return .denied81        default: return .undetermined82        }83    }8485    public func requestPermission() async -> Bool {86        if permission == .granted { return true }87        return await AVAudioApplication.requestRecordPermission()88    }8990    /// AAC, mono, 44.1 kHz, 64 kbit/s: small files the transcription engine reads (m4a).91    public static let settings: [String: Any] = [92        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),93        AVSampleRateKey: 44_100.0,94        AVNumberOfChannelsKey: 1,95        AVEncoderBitRateKey: 64_000,96        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,97    ]9899    public func start(to url: URL) throws {100        #if os(iOS)101        do {102            let session = AVAudioSession.sharedInstance()103            try session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetooth])104            try session.setActive(true)105        } catch { throw AudioEngineError.cannotRecord(error.localizedDescription) }106        #endif107        do {108            let recorder = try AVAudioRecorder(url: url, settings: Self.settings)109            recorder.isMeteringEnabled = true110            guard recorder.prepareToRecord(), recorder.record() else { throw AudioEngineError.cannotRecord("record() refused") }111            self.recorder = recorder112        } catch let error as AudioEngineError { throw error } catch { throw AudioEngineError.cannotRecord(error.localizedDescription) }113    }114115    public func pause() { recorder?.pause() }116    public func resume() { recorder?.record() }117118    @discardableResult119    public func stop() -> TimeInterval {120        guard let recorder else { return 0 }121        let duration = recorder.currentTime122        recorder.stop()123        self.recorder = nil124        #if os(iOS)125        try? AVAudioSession.sharedInstance().setActive(false, options: [.notifyOthersOnDeactivation])126        #endif127        return duration128    }129130    public var currentTime: TimeInterval { recorder?.currentTime ?? 0 }131132    public var level: Double {133        guard let recorder, recorder.isRecording else { return 0 }134        recorder.updateMeters()135        return AudioLevel.normalized(decibels: Double(recorder.averagePower(forChannel: 0)))136    }137}138139public enum AudioLevel {140    /// Maps an average power in dBFS (−160…0) to 0…1 for a meter: silence below −50 dB, full at 0 dB.141    public static func normalized(decibels: Double) -> Double {142        guard decibels.isFinite else { return 0 }143        return min(1, max(0, (decibels + 50) / 50))144    }145}146147/// The real player.148@MainActor149public final class SystemAudioPlayer: AudioPlaying {150    private var player: AVAudioPlayer?151    private var delegate: FinishDelegate?152    public var onFinish: (@MainActor () -> Void)?153    /// 0 in the tests so that nothing is ever heard.154    public var volume: Float = 1 { didSet { player?.volume = volume } }155156    public init() {}157158    @discardableResult159    public func load(url: URL) throws -> TimeInterval {160        do {161            let player = try AVAudioPlayer(contentsOf: url)162            player.enableRate = true163            player.rate = Float(rate)164            player.volume = volume165            let delegate = FinishDelegate { [weak self] in self?.onFinish?() }166            player.delegate = delegate167            guard player.prepareToPlay() else { throw AudioEngineError.cannotPlay("prepareToPlay() refused") }168            self.player = player169            self.delegate = delegate170            return player.duration171        } catch let error as AudioEngineError { throw error } catch { throw AudioEngineError.cannotPlay(error.localizedDescription) }172    }173174    public func play() {175        #if os(iOS)176        let session = AVAudioSession.sharedInstance()177        if session.category != .playAndRecord { try? session.setCategory(.playback, mode: .spokenAudio) }178        try? session.setActive(true)179        #endif180        player?.play()181    }182183    public func pause() { player?.pause() }184    public func seek(to time: TimeInterval) { player?.currentTime = min(max(0, time), duration) }185    public var currentTime: TimeInterval { player?.currentTime ?? 0 }186    public var duration: TimeInterval { player?.duration ?? 0 }187    public var isPlaying: Bool { player?.isPlaying ?? false }188    public var rate: Double = 1 { didSet { player?.rate = Float(rate) } }189190    private final class FinishDelegate: NSObject, AVAudioPlayerDelegate, @unchecked Sendable {191        let finished: @MainActor () -> Void192        init(finished: @escaping @MainActor () -> Void) { self.finished = finished }193        func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {194            let finished = finished195            Task { @MainActor in finished() }196        }197    }198}199
Files main
Menu

Theme