SPB Git

Repository Public

VoiceSample.swift 6.7 KB 132 lines swift

1// SP Notes iOS2// File: Features/Voice/VoiceSample.swift3// Description: A short generated tone as an m4a file, and the sample voice note of the seeded workspace (« Note vocale »: the4//              tone, a transcript and an AI summary taken from the recorded server answer). Also the DEBUG microphone stand-ins5//              used for screenshots and UI tests, where no microphone can be driven (`SPNOTES_FAKE_MIC=demo|denied|restricted`).6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import AVFoundation10import Foundation11import SPNotesCore1213/// Writes a sine tone as AAC in an m4a container (the format of the recorder).14enum ToneFile {15    static func write(to url: URL, seconds: Double, frequency: Double = 440, amplitude: Float = 0.2) throws {16        let sampleRate = 44_100.017        guard let format = AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: 1) else { throw CocoaError(.fileWriteUnknown) }18        let file = try AVAudioFile(forWriting: url, settings: SystemAudioRecorder.settings, commonFormat: .pcmFormatFloat32, interleaved: false)19        let total = Int(seconds * sampleRate), chunk = 409620        var written = 021        while written < total {22            let count = min(chunk, total - written)23            guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(count)), let samples = buffer.floatChannelData?[0] else { throw CocoaError(.fileWriteUnknown) }24            buffer.frameLength = AVAudioFrameCount(count)25            for i in 0..<count {26                let t = Double(written + i) / sampleRate27                // a short fade at both ends: no click28                let edge = Float(min(1, min(t, seconds - t) / 0.02))29                samples[i] = amplitude * edge * Float(sin(2 * .pi * frequency * t))30            }31            try file.write(from: buffer)32            written += count33        }34    }35}3637enum VoiceSample {38    static let noteNumber = 1939    static var noteID: String { SampleData.id(noteNumber) }4041    /// The transcript and summary of the recorded server answer (API-NEXT-AI §6.2), re-timed to the two seconds of the tone.42    static func block(attachmentId: String, recordedAt: Date) -> AudioBlock {43        var block = AudioBlock(attachmentId: attachmentId, duration: 2, title: "Réunion du 19 novembre", recordedAt: recordedAt)44        block.transcript = [TranscriptSegment(t: 0, text: "Réunion du 19 novembre. Nous retenons le taux fixe de 5 ans."),45                            TranscriptSegment(t: 1.1, text: "Marie envoie les documents à la banque lundi matin.")]46        block.transcriptStatus = .done47        block.transcriptEngine = "openai:whisper-1"48        block[attr: "summary"] = .object([49            "text": .string("Réunion du 19 novembre. Ils retiennent un taux fixe de 5 ans. Marie enverra les documents à la banque lundi matin."),50            "decisions": .array([.string("Ils retiennent le taux fixe de 5 ans.")]),51            "tasks": .array([.string("Marie envoie les documents à la banque lundi matin.")]),52            "model": .string("gpt-5.4-mini"), "at": .string("2026-11-19T18:22:36.405Z"),53        ])54        return block55    }5657    /// Adds the tone and the `audio` block to the seeded note. Returns the node (nil when the note is not there).58    @MainActor59    @discardableResult60    static func attach(to app: AppModel, noteId: String = noteID) async -> PMNode? {61        guard let page = try? await app.store.page(id: noteId), var document = try? NoteDocument(json: page.content),62              let url = try? MediaTemp.newFileURL(named: "Réunion du 19 novembre.m4a") else { return nil }63        defer { MediaTemp.discard(url) }64        do {65            try ToneFile.write(to: url, seconds: 2)66            let file = try await app.attach(fileAt: url, to: noteId, filename: url.lastPathComponent, mime: "audio/mp4")67            guard let id = file.stringAttr("attachmentId") else { return nil }68            let node = block(attachmentId: id, recordedAt: Date(timeIntervalSince1970: 1_795_112_551)).node()69            document.insert(lines: [Line(blockAtom: node, path: [])], at: document.lines.count)70            _ = try await app.save(noteId: noteId, title: page.title, document: document)71            return node72        } catch { return nil }73    }74}7576/// DEBUG stand-ins for the microphone. `recorder()` is nil in a release build and when the variable is not set.77@MainActor78enum VoiceDebug {79    static func recorder() -> VoiceRecorderModel? {80        #if DEBUG81        switch ProcessInfo.processInfo.environment["SPNOTES_FAKE_MIC"] {82        case "demo": return VoiceRecorderModel(recorder: DemoAudioRecorder(), authorizer: FixedMicrophone(status: .granted))83        case "denied": return VoiceRecorderModel(recorder: DemoAudioRecorder(), authorizer: FixedMicrophone(status: .denied))84        case "restricted": return VoiceRecorderModel(recorder: DemoAudioRecorder(), authorizer: FixedMicrophone(status: .restricted))85        default: return nil86        }87        #else88        return nil89        #endif90    }91}9293#if DEBUG94struct FixedMicrophone: MicrophoneAuthorizing {95    var status: MicrophonePermission96    func request() async -> MicrophonePermission { status == .undetermined ? .granted : status }97}9899/// Not a microphone: a clock, a speech-like level curve and, at the end, a tone of the elapsed length. Screenshots and UI tests only.100@MainActor101final class DemoAudioRecorder: AudioRecording {102    var onEvent: ((RecorderEvent) -> Void)?103    private var url: URL?104    private var accumulated: Double = 0105    private var resumedAt: Date?106    /// The clock starts here, so a screenshot taken right after the launch shows a recording under way.107    var offset: Double = 37108109    var currentTime: Double { offset + accumulated + (resumedAt.map { Date().timeIntervalSince($0) } ?? 0) }110111    func averagePower() -> Float {112        guard resumedAt != nil else { return -160 }113        let t = currentTime114        // syllables inside phrases, with breaths between the phrases115        let phrase = max(0, sin(t * 1.3) * 0.5 + 0.55)116        let syllables = pow(abs(sin(t * 9.1)), 1.6) * 0.75 + abs(sin(t * 23)) * 0.25117        return Float(-52 + 46 * phrase * syllables)118    }119120    func start(to url: URL) throws { self.url = url; accumulated = 0; resumedAt = Date() }121    func pause() { if let resumedAt { accumulated += Date().timeIntervalSince(resumedAt) }; resumedAt = nil }122    func resume() -> Bool { resumedAt = Date(); return true }123    func stop() -> Double {124        pause()125        let duration = offset + accumulated126        if let url { try? ToneFile.write(to: url, seconds: min(2, max(0.5, accumulated))) }127        return duration128    }129    func cancel() { pause(); if let url { try? FileManager.default.removeItem(at: url) }; url = nil }130}131#endif132
Files main
Menu

Theme