139 lines
5.4 KiB
Swift
139 lines
5.4 KiB
Swift
import AVFoundation
|
|
import CoreMedia
|
|
import Speech
|
|
import os
|
|
|
|
@available(iOS 26.0, *)
|
|
@MainActor
|
|
final class ContinuousDictation {
|
|
private static var assetPreparation: Task<Void, Never>?
|
|
private let transcriber: DictationTranscriber
|
|
private let analyzer: SpeechAnalyzer
|
|
private let input: AsyncStream<AnalyzerInput>
|
|
let audioInput: AudioInput
|
|
private var task: Task<Void, Never>?
|
|
|
|
static func prepare(locale: Locale, inputFormat: AVAudioFormat, context: [String]) async throws -> ContinuousDictation? {
|
|
guard let locale = await DictationTranscriber.supportedLocale(equivalentTo: locale) else { return nil }
|
|
let transcriber = DictationTranscriber(locale: locale, preset: .progressiveLongDictation)
|
|
let assetStatus = await AssetInventory.status(forModules: [transcriber])
|
|
if assetStatus == .supported, assetPreparation == nil {
|
|
// Keep the first recording responsive while iOS prepares its local model.
|
|
assetPreparation = Task(priority: .utility) {
|
|
if let installation = try? await AssetInventory.assetInstallationRequest(supporting: [transcriber]) {
|
|
try? await installation.downloadAndInstall()
|
|
}
|
|
}
|
|
}
|
|
guard assetStatus == .installed,
|
|
let format = await SpeechAnalyzer.bestAvailableAudioFormat(compatibleWith: [transcriber], considering: inputFormat),
|
|
let converter = AVAudioConverter(from: inputFormat, to: format) else { return nil }
|
|
|
|
let analyzer = SpeechAnalyzer(modules: [transcriber])
|
|
let hints = AnalysisContext()
|
|
hints.contextualStrings[.general] = context
|
|
try await analyzer.setContext(hints)
|
|
try await analyzer.prepareToAnalyze(in: format)
|
|
return ContinuousDictation(transcriber: transcriber, analyzer: analyzer, converter: converter)
|
|
}
|
|
|
|
private init(transcriber: DictationTranscriber, analyzer: SpeechAnalyzer, converter: AVAudioConverter) {
|
|
self.transcriber = transcriber
|
|
self.analyzer = analyzer
|
|
let (stream, continuation) = AsyncStream.makeStream(of: AnalyzerInput.self)
|
|
input = stream
|
|
audioInput = AudioInput(converter: converter, continuation: continuation)
|
|
}
|
|
|
|
func start(onUpdate: @escaping (String, Bool) -> Void, onFinish: @escaping (Bool) -> Void) {
|
|
task = Task { [analyzer, transcriber, input, audioInput] in
|
|
do {
|
|
async let analysis: Void = Self.analyze(analyzer, input: input)
|
|
for try await result in transcriber.results {
|
|
guard !Task.isCancelled else { return }
|
|
onUpdate(String(result.text.characters), result.isFinal)
|
|
}
|
|
try await analysis
|
|
if !Task.isCancelled { onFinish(!audioInput.failed) }
|
|
} catch {
|
|
if !Task.isCancelled { onFinish(false) }
|
|
}
|
|
}
|
|
}
|
|
|
|
private nonisolated static func analyze(_ analyzer: SpeechAnalyzer, input: AsyncStream<AnalyzerInput>) async throws {
|
|
do {
|
|
if let last = try await analyzer.analyzeSequence(input) {
|
|
try await analyzer.finalizeAndFinish(through: last)
|
|
} else {
|
|
await analyzer.cancelAndFinishNow()
|
|
}
|
|
} catch {
|
|
await analyzer.cancelAndFinishNow()
|
|
throw error
|
|
}
|
|
}
|
|
|
|
func stop() {
|
|
audioInput.finish()
|
|
}
|
|
|
|
func cancel() {
|
|
audioInput.finish()
|
|
task?.cancel()
|
|
let analyzer = self.analyzer
|
|
Task { await analyzer.cancelAndFinishNow() }
|
|
}
|
|
|
|
// The audio tap owns the converter. The result task only reads the locked failure flag.
|
|
final class AudioInput: @unchecked Sendable {
|
|
private let converter: AVAudioConverter
|
|
private let continuation: AsyncStream<AnalyzerInput>.Continuation
|
|
private let failure = OSAllocatedUnfairLock(initialState: false)
|
|
var failed: Bool { failure.withLock { $0 } }
|
|
|
|
init(converter: AVAudioConverter, continuation: AsyncStream<AnalyzerInput>.Continuation) {
|
|
self.converter = converter
|
|
self.continuation = continuation
|
|
converter.primeMethod = .none
|
|
}
|
|
|
|
func append(_ buffer: AVAudioPCMBuffer) {
|
|
guard buffer.frameLength > 0 else { return }
|
|
let format = converter.outputFormat
|
|
let ratio = format.sampleRate / buffer.format.sampleRate
|
|
let capacity = AVAudioFrameCount(ceil(Double(buffer.frameLength) * ratio))
|
|
guard let output = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: capacity) else {
|
|
markFailed()
|
|
return
|
|
}
|
|
|
|
var supplied = false
|
|
var error: NSError?
|
|
let status = converter.convert(to: output, error: &error) { _, inputStatus in
|
|
if supplied {
|
|
inputStatus.pointee = .noDataNow
|
|
return nil
|
|
}
|
|
supplied = true
|
|
inputStatus.pointee = .haveData
|
|
return buffer
|
|
}
|
|
guard status != .error else {
|
|
markFailed()
|
|
return
|
|
}
|
|
if output.frameLength > 0 { continuation.yield(AnalyzerInput(buffer: output)) }
|
|
}
|
|
|
|
func finish() {
|
|
continuation.finish()
|
|
}
|
|
|
|
private func markFailed() {
|
|
failure.withLock { $0 = true }
|
|
finish()
|
|
}
|
|
}
|
|
}
|