SPB Git

Repository Public

VoiceRecorder.swift 3.9 KB 84 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Voice/VoiceRecorder.swift4//  Description: Dictation: records the microphone (explicit permission) and has the backend transcribe it.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import AVFoundation11import Observation1213@MainActor14@Observable15final class VoiceRecorder {16    enum State: Equatable { case idle, recording(since: Date), transcribing }17    private(set) var state: State = .idle18    var lastError: String?1920    @ObservationIgnored private var recorder: AVAudioRecorder?21    @ObservationIgnored private var fileURL: URL?22    @ObservationIgnored private let api: ChatAPI23    /// The server refuses audio above 25 MB; at 64 kbit/s that is far beyond this limit.24    static let maxDuration: TimeInterval = 10 * 602526    init(api: ChatAPI) { self.api = api }2728    var isRecording: Bool { if case .recording = state { return true } else { return false } }2930    /// Asks for the microphone the first time, then records AAC mono into a protected temporary file.31    func start() async {32        guard state == .idle else { return }33        lastError = nil34        guard await AVAudioApplication.requestRecordPermission() else {35            lastError = String(localized: "Micro refusé. Autorise-le dans Réglages → SP Chat pour dicter.")36            return37        }38        do {39            let session = AVAudioSession.sharedInstance()40            try session.setCategory(.playAndRecord, mode: .spokenAudio, options: [.defaultToSpeaker, .allowBluetoothHFP])41            try session.setActive(true)42            let url = FileManager.default.temporaryDirectory.appendingPathComponent("dictee-\(UUID().uuidString).m4a")43            let settings: [String: Any] = [AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: 44_100, AVNumberOfChannelsKey: 1, AVEncoderBitRateKey: 64_000, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue]44            let r = try AVAudioRecorder(url: url, settings: settings)45            guard r.record(forDuration: Self.maxDuration) else { throw NSError(domain: "voice", code: 1) }46            try? FileManager.default.setAttributes([.protectionKey: FileProtectionType.completeUnlessOpen], ofItemAtPath: url.path)47            recorder = r; fileURL = url48            state = .recording(since: Date())49        } catch {50            cleanup()51            lastError = String(localized: "L’enregistrement n’a pas pu démarrer.")52        }53    }5455    /// Stops and returns the transcription (nil when cancelled, too short, or failed — `lastError` says why).56    func finish(language: String?) async -> String? {57        guard case .recording(let since) = state, let recorder, let fileURL else { return nil }58        let duration = recorder.currentTime > 0 ? recorder.currentTime : Date().timeIntervalSince(since)59        recorder.stop()60        try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)61        guard duration >= 0.4, let data = try? Data(contentsOf: fileURL), !data.isEmpty else { cleanup(); return nil }62        state = .transcribing63        defer { cleanup() }64        do {65            let text = try await api.transcribe(audio: data, filename: "dictee.m4a", mime: "audio/mp4", language: language, durationSec: duration)66            return text.trimmingCharacters(in: .whitespacesAndNewlines)67        } catch let e as APIError {68            if e.kind != .cancelled { lastError = e.kind == .network ? String(localized: "Hors ligne : la dictée n’a pas été transcrite.") : e.message }69            return nil70        } catch { lastError = String(localized: "Transcription impossible."); return nil }71    }7273    func cancel() {74        recorder?.stop()75        try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)76        cleanup()77    }7879    private func cleanup() {80        if let fileURL { try? FileManager.default.removeItem(at: fileURL) }81        recorder = nil; fileURL = nil; state = .idle82    }83}84
Files main
Menu

Theme