item-atlas/apps/ios/ItemAtlas/VoiceCapture.swift

274 lines
10 KiB
Swift

import AVFoundation
import Observation
import Speech
@MainActor
@Observable
final class VoiceCapture {
enum Phase { case idle, preparing, recording, finishing }
static let maximumDuration = 25
private static let locale = Locale(identifier: "zh-CN")
private(set) var phase: Phase = .idle
private(set) var elapsedSeconds = 0
private(set) var transcript = ""
private(set) var error: String?
private let engine = AVAudioEngine()
private var timer: Task<Void, Never>?
private var sessionID: UUID?
private var tapInstalled = false
private var audioActive = false
private var completion: ((String, Bool) -> Void)?
private var endInput: (() -> Void)?
private var cancelRecognition: (() -> Void)?
private var completed: [String] = []
private var preview = ""
private var legacy = LegacyTranscription()
func start(context: [String], completion: @escaping (String, Bool) -> Void) async {
guard phase == .idle else { return }
let id = UUID()
sessionID = id
error = nil
phase = .preparing
let microphone = await AVAudioApplication.requestRecordPermission()
guard sessionID == id else { return }
guard microphone else {
fail("麦克风权限已关闭。可以在系统设置中开启,或直接打字。")
return
}
let authorized = await withCheckedContinuation { continuation in
// Speech can invoke this callback off the main actor.
SFSpeechRecognizer.requestAuthorization { @Sendable status in
continuation.resume(returning: status == .authorized)
}
}
guard sessionID == id else { return }
guard authorized else {
fail("语音识别权限已关闭。可以在系统设置中开启,或直接打字。")
return
}
do {
let audio = AVAudioSession.sharedInstance()
try audio.setCategory(.record, mode: .measurement)
try audio.setActive(true)
audioActive = true
let input = engine.inputNode
let format = input.outputFormat(forBus: 0)
guard format.sampleRate > 0, format.channelCount > 0 else {
fail("当前没有可录音的麦克风。")
return
}
let hints = Array(context.prefix(60))
if #available(iOS 26.0, *),
let dictation = try? await ContinuousDictation.prepare(
locale: Self.locale, inputFormat: format, context: hints
) {
guard sessionID == id else { dictation.cancel(); return }
let sink = dictation.audioInput
input.installTap(onBus: 0, bufferSize: 1024, format: format) { @Sendable buffer, _ in
sink.append(buffer)
}
endInput = dictation.stop
cancelRecognition = dictation.cancel
dictation.start { [weak self] text, final in
self?.receivePhrase(id: id, text: text, final: final)
} onFinish: { [weak self] success in
guard let self, self.sessionID == id else { return }
self.finish(final: success && self.phase == .finishing)
}
} else {
guard sessionID == id else { return }
guard startLegacy(id: id, input: input, format: format, context: hints) else {
fail("本机暂时无法转写普通话。可以用键盘听写或直接打字。")
return
}
}
tapInstalled = true
self.completion = completion
engine.prepare()
try engine.start()
phase = .recording
countRecordingTime()
} catch {
fail("麦克风暂时无法使用。")
}
}
func stop() {
if phase == .preparing {
cancel()
return
}
guard phase == .recording else { return }
phase = .finishing
stopMicrophone()
endInput?()
timer?.cancel()
timer = Task { [weak self] in
try? await Task.sleep(for: .seconds(6))
if !Task.isCancelled { self?.finish(final: false) }
}
}
func cancel() {
sessionID = nil
stopMicrophone()
cancelRecognition?()
cancelRecognition = nil
endInput = nil
timer?.cancel()
timer = nil
completion = nil
phase = .idle
elapsedSeconds = 0
transcript = ""
completed = []
preview = ""
legacy = LegacyTranscription()
if audioActive {
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
audioActive = false
}
}
private func countRecordingTime() {
let clock = ContinuousClock()
let start = clock.now
timer = Task { [weak self] in
for second in 1...Self.maximumDuration {
try? await clock.sleep(until: start.advanced(by: .seconds(second)))
guard !Task.isCancelled, let self else { return }
self.elapsedSeconds = second
}
self?.stop()
}
}
private func receivePhrase(id: UUID, text: String, final: Bool) {
guard sessionID == id else { return }
let phrase = text.trimmingCharacters(in: .whitespacesAndNewlines)
if final {
if !phrase.isEmpty { completed.append(phrase) }
preview = ""
} else {
preview = phrase
}
transcript = (preview.isEmpty ? completed : completed + [preview]).joined(separator: "\n")
}
private func startLegacy(id: UUID, input: AVAudioInputNode, format: AVAudioFormat, context: [String]) -> Bool {
guard let recognizer = SFSpeechRecognizer(locale: Self.locale),
recognizer.supportsOnDeviceRecognition, recognizer.isAvailable else { return false }
let request = SFSpeechAudioBufferRecognitionRequest()
request.requiresOnDeviceRecognition = true
request.shouldReportPartialResults = true
request.taskHint = .dictation
request.contextualStrings = context
let sink = BufferSink(request)
input.installTap(onBus: 0, bufferSize: 1024, format: format) { @Sendable buffer, _ in
sink.append(buffer)
}
let recognition = recognizer.recognitionTask(with: request) { @Sendable [weak self] result, error in
let text = result?.bestTranscription.formattedString
let segments = result?.bestTranscription.segments
let start = segments?.first?.timestamp ?? 0
let last = segments?.last
let end = (last?.timestamp ?? 0) + (last?.duration ?? 0)
let final = result?.isFinal == true
let failed = error != nil
let now = ContinuousClock().now
Task { @MainActor in
guard let self, self.sessionID == id else { return }
if let text, !text.isEmpty {
self.legacy.update(text, start: start, end: end, at: now, final: final)
self.transcript = self.legacy.text
}
if final || failed { self.finish(final: final && !failed && self.phase == .finishing) }
}
}
endInput = request.endAudio
cancelRecognition = { recognition.cancel(); _ = recognizer }
return true
}
private func stopMicrophone() {
guard tapInstalled else { return }
engine.stop()
engine.inputNode.removeTap(onBus: 0)
tapInstalled = false
}
private func finish(final: Bool) {
let text = transcript.trimmingCharacters(in: .whitespacesAndNewlines)
let callback = completion
cancel()
if text.isEmpty {
error = "没有听清。可以再录一遍,或直接输入。"
} else {
if !final { error = "转写提前结束,已保留听到的文字。请先核对。" }
callback?(text, final)
}
}
private func fail(_ message: String) {
cancel()
error = message
}
private final class BufferSink: @unchecked Sendable {
private let request: SFSpeechAudioBufferRecognitionRequest
init(_ request: SFSpeechAudioBufferRecognitionRequest) { self.request = request }
func append(_ buffer: AVAudioPCMBuffer) { request.append(buffer) }
}
}
// The older API may give a fresh utterance after a pause instead of extending its previous result.
struct LegacyTranscription {
private var committed: [String] = []
private var current = ""
private var lastUpdate: ContinuousClock.Instant?
private var previousEnd: TimeInterval = 0
var text: String { (current.isEmpty ? committed : committed + [current]).joined(separator: "\n") }
mutating func update(_ value: String, start: TimeInterval, end: TimeInterval,
at now: ContinuousClock.Instant, final: Bool) {
let next = value.trimmingCharacters(in: .whitespacesAndNewlines)
guard !next.isEmpty else { return }
let nextKey = comparisonKey(next)
let currentKey = comparisonKey(current)
if final, let first = committed.first.map(comparisonKey), !first.isEmpty, end > start,
nextKey.hasPrefix(first) {
// The final result can include the complete audio after its partials reset.
committed = []
current = next
return
}
let prefix = zip(nextKey, currentKey).prefix { $0 == $1 }.count
let pause = lastUpdate.map { $0.duration(to: now) >= .milliseconds(700) } ?? false
let separateRange = start > previousEnd + 0.15 && previousEnd > 0
if !final && !separateRange && pause && prefix == nextKey.count && nextKey.count < currentKey.count {
return
}
let newUntimedPhrase = (end <= start || previousEnd == 0) && pause &&
currentKey.count - prefix >= max(2, currentKey.count / 2)
if !current.isEmpty && (separateRange || newUntimedPhrase) {
committed.append(current)
}
current = next
previousEnd = end
lastUpdate = now
}
private func comparisonKey(_ text: String) -> String {
String(text.filter { !$0.isPunctuation && !$0.isWhitespace })
}
}