知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
feat(ios): Their language can be Auto-detect: listening and imports hear which language is spoken, as on the Mac
wquguru77a51da96d41
diff --git a/Sources/Cicada/FileImport.swift b/Sources/Cicada/FileImport.swiftindex c136b8d..abee1fe 100644--- a/Sources/Cicada/FileImport.swift+++ b/Sources/Cicada/FileImport.swift@@ -351,10 +351,6 @@ final class FileImporter: ObservableObject {private func language(of pcm: URL) async -> Lang {if let fixed = sourceLanguages.first(where: { $0.locale == settings.importLanguage }) { return fixed }- #if CICADA_IOS- // iOS always names the language (对方说); LanguageDetector is the Mac's.- return sourceLanguages[0]- #elselet langs = await Self.installed()guard langs.count > 1 else { return langs.first ?? sourceLanguages[0] }phase = .detecting@@ -373,7 +369,6 @@ final class FileImporter: ObservableObject {debugLog("import: language scores \(scores.map { String(format: "%@=%.2f", $0.key, $0.value) }.sorted())")let best = scores.max { $0.value < $1.value }?.keyreturn langs.first { $0.locale == best } ?? langs[0]- #endif}/// With no long pause the recognizer hands back minutes as one result (a speech, a fluentdiff --git a/Sources/Cicada/LanguageDetector.swift b/Sources/Cicada/LanguageDetector.swiftindex c0c176c..9898d00 100644--- a/Sources/Cicada/LanguageDetector.swift+++ b/Sources/Cicada/LanguageDetector.swift@@ -1,8 +1,4 @@-import AppKitimport AVFoundation-import AudioToolbox-import CoreAudio-import CoreMedia// MARK: - Spoken language detectiondiff --git a/ios/Sources/Cicada/CicadaApp.swift b/ios/Sources/Cicada/CicadaApp.swiftindex df0038e..3b2fcba 100644--- a/ios/Sources/Cicada/CicadaApp.swift+++ b/ios/Sources/Cicada/CicadaApp.swift@@ -53,17 +53,27 @@ enum Pref {static let silenceMinutes = "silenceMinutes"static var speakerMode: Bool { UserDefaults.standard.string(forKey: hear) == "speaker" }- /// 对方说 on iOS: one language the user picks (detecting it comes later); the Mac's "auto" reads as English.+ /// 对方说 is 自动识别: listening and imports hear which language it is (LanguageDetector).+ static var sourceAuto: Bool { (UserDefaults.standard.string(forKey: source) ?? "auto") == "auto" }++ /// 对方说 as one language: the one picked, or with 自动识别 the one heard last (the Mac's+ /// lastDetected), else the likeliest for this phone. Face to face and model downloads use it.static var sourceLang: Lang {- let v = UserDefaults.standard.string(forKey: source) ?? "en-US"- return sourceLanguages.first { $0.locale == v } ?? sourceLanguages[0]+ let v = UserDefaults.standard.string(forKey: source) ?? "auto"+ if let lang = sourceLanguages.first(where: { $0.locale == v }) { return lang }+ let last = UserDefaults.standard.string(forKey: lastDetected)+ return likelySourceLanguages(last: last, systemLanguages: Locale.preferredLanguages).first ?? sourceLanguages[0]}+ /// The language 自动识别 heard last, as the Mac keeps it.+ static let lastDetected = "lastDetected"/// 对方说 in the UI's language ("英语", "English"), as the Mac's menu shows it.static func name(of lang: Lang) -> String {Locale.current.localizedString(forLanguageCode: lang.code) ?? lang.name}- static var sourceName: String { name(of: sourceLang) }+ /// 对方说's code for 翻译成: with 自动识别, none yet (跟随系统 is my language until one is heard).+ static var sourceCode: String { sourceAuto ? "auto" : sourceLang.code }+ static var sourceName: String { sourceAuto ? L("自动识别") : name(of: sourceLang) }/// "英 → 中" for two translation codes, as a meeting row says it.static func pairText(_ source: String, _ target: String) -> String {@@ -212,7 +222,7 @@ final class AppModel: ObservableObject {@Published var devWindow: CGSize?init() {- UserDefaults.standard.register(defaults: [Pref.source: "en-US", Pref.voices: true, Pref.model: LingClient.models[0], Pref.notesLanguage: "mine",+ UserDefaults.standard.register(defaults: [Pref.source: "auto", Pref.voices: true, Pref.model: LingClient.models[0], Pref.notesLanguage: "mine",Pref.fixMisheard: true, Pref.askNames: true, Pref.recordAudio: true,Pref.silenceEnd: "prompt", Pref.silenceMinutes: 10.0])TranscriptExport.voices = UserDefaults.standard.bool(forKey: Pref.voices)@@ -248,7 +258,7 @@ final class AppModel: ObservableObject {// 纪要 first, as the Mac's notes window; without a key there are none, so 字幕.livePage = ling.hasKey ? .notes : .subtitlesfixes.meetingStarted()- room.start(source: Pref.sourceLang.locale, target: Pref.target(for: Pref.sourceLang.code), voices: UserDefaults.standard.bool(forKey: Pref.voices),+ room.start(source: Pref.sourceAuto ? "auto" : Pref.sourceLang.locale, target: Pref.target(for: Pref.sourceCode), voices: UserDefaults.standard.bool(forKey: Pref.voices),speaker: Pref.speakerMode)}diff --git a/ios/Sources/Cicada/FaceToFace.swift b/ios/Sources/Cicada/FaceToFace.swiftindex 5393fe0..1f4ab2a 100644--- a/ios/Sources/Cicada/FaceToFace.swift+++ b/ios/Sources/Cicada/FaceToFace.swift@@ -92,7 +92,8 @@ final class FaceToFace: ObservableObject {mine = mtheirs = tUserDefaults.standard.set(m.locale, forKey: Pref.myLang)- UserDefaults.standard.set(t.locale, forKey: Pref.source)+ // With 自动识别 for listening it stays on: their language is the one heard last.+ UserDefaults.standard.set(t.locale, forKey: Pref.sourceAuto ? Pref.lastDetected : Pref.source)}// MARK: The screendiff --git a/ios/Sources/Cicada/Importing.swift b/ios/Sources/Cicada/Importing.swiftindex b019805..cb5d94a 100644--- a/ios/Sources/Cicada/Importing.swift+++ b/ios/Sources/Cicada/Importing.swift@@ -10,10 +10,11 @@ import UniformTypeIdentifiers// records the system keeps the app running behind other apps (BGContinuedProcessingTask) and shows// its progress.-/// 对方说 and 翻译成 as the iOS app has them: an import is in the language the user listens to.+/// 对方说 and 翻译成 as the iOS app has them: an import is in the language the user listens to+/// (自动识别: FileImporter hears it).@MainActorfinal class ImportPrefs: ImportSettings {- var importLanguage: String { Pref.sourceLang.locale }+ var importLanguage: String { Pref.sourceAuto ? "auto" : Pref.sourceLang.locale }var speakerVoices: Bool { UserDefaults.standard.bool(forKey: Pref.voices) }func resolvedTarget(source: String?) -> String { Pref.target(for: source ?? Pref.sourceLang.code) }}diff --git a/ios/Sources/Cicada/LiveViews.swift b/ios/Sources/Cicada/LiveViews.swiftindex 5ec928c..328ad5e 100644--- a/ios/Sources/Cicada/LiveViews.swift+++ b/ios/Sources/Cicada/LiveViews.swift@@ -59,7 +59,7 @@ struct LiveDot: View {struct ListenBar: View {@EnvironmentObject var model: AppModel@EnvironmentObject var room: RoomListen- @AppStorage(Pref.source) private var source = "en-US"+ @AppStorage(Pref.source) private var source = "auto"@AppStorage(Pref.target) private var target = "system"@AppStorage(Pref.hear) private var hear = "room"/// Glass on the ground (iPhone); white on the iPad's glass sidebar.@@ -94,6 +94,7 @@ struct ListenBar: View {Text(hear == "speaker" ? L("别戴耳机,字幕会浮在小窗里") : L("听不到其他 app 的声音,线上会议请用电脑版"))}Picker(selection: $source) {+ Text("自动识别").tag("auto")ForEach(sourceLanguages, id: \.locale) { Text(Pref.name(of: $0)).tag($0.locale) }} label: { Text("对方说") }Picker(selection: $target) {@@ -101,7 +102,7 @@ struct ListenBar: View {ForEach(targetLanguages, id: \.code) { Text($0.name).tag($0.code) }} label: { Text("翻译成") }} label: {- Text(verbatim: (hear == "speaker" ? L("外放") + " · " : "") + "\(Pref.sourceName) → \(targetName(Pref.target(for: Pref.sourceLang.code)))")+ Text(verbatim: (hear == "speaker" ? L("外放") + " · " : "") + "\(Pref.sourceName) → \(targetName(Pref.target(for: Pref.sourceCode)))").font(.subheadline).foregroundStyle(Ink.secondary).lineLimit(1).minimumScaleFactor(0.75).frame(maxWidth: .infinity, alignment: .leading).frame(minHeight: 44)diff --git a/ios/Sources/Cicada/RoomListen.swift b/ios/Sources/Cicada/RoomListen.swiftindex 996407b..250d109 100644--- a/ios/Sources/Cicada/RoomListen.swift+++ b/ios/Sources/Cicada/RoomListen.swift@@ -3,8 +3,9 @@ import Foundation/// 听会议室 on iPhone and iPad: the microphone → the shared recognizer (`Recognition`) → the shared/// translation chain → the meeting record, with live notes from the shared `NotesEngine`. The Mac's-/// `ListenEngine` is bound to Core Audio and AppKit; this is the same pipeline cut down to one source-/// and one language the user picked (对方说; detecting it comes later).+/// `ListenEngine` is bound to Core Audio and AppKit; this is the same pipeline cut down to one source.+/// 对方说 is one language, or 自动识别: listening starts in the likeliest one and the first words+/// settle it (`LanguageDetector`, as on the Mac), heard again in another language if that's the one.@MainActorfinal class RoomListen: ObservableObject {/// One sentence on the 字幕 page.@@ -66,6 +67,22 @@ final class RoomListen: ObservableObject {/// The microphone heard something loud enough to be a voice, for keeping a meeting with no lines.private var heardVoice = false+ /// 自动识别: until the language is settled, finished lines wait in `held` (written once it is+ /// the one listened in) and the microphone's audio is kept to hear again in another.+ private var auto = false+ private var settled = true+ private var candidates: [Lang] = []+ private var detection = LanguageDetection()+ private var held: [Recognition.Piece] = []+ private var detector: Task<Void, Never>?+ private var lastVoiceAt = Date.distantPast+ /// The recognizer in use: pieces from one replaced (another language) are dropped.+ private var generation = 0+ /// Models compared at once: each check transcribes the clip with every one of them.+ private static let maxCandidates = 4+ /// Kept audio after which the language stays as it is (nobody spoke a clear sentence).+ private static let giveUpSeconds = 90.0+init(store: SessionStore, translator: TranslationService, notes: NotesEngine) {self.store = storeself.translator = translator@@ -103,7 +120,10 @@ final class RoomListen: ObservableObject {speakerMode = speakerpaused = falseuserPaused = false- lang = sourceLanguages.first { $0.locale == source } ?? sourceLanguages[0]+ auto = source == "auto"+ settled = true+ held = []+ lang = sourceLanguages.first { $0.locale == source } ?? Pref.sourceLangself.target = targetstatus = L("正在准备…")isRunning = true@@ -138,6 +158,18 @@ final class RoomListen: ObservableObject {return}do {+ settled = true+ held = []+ if auto {+ candidates = await autoCandidates()+ guard isRunning else { return }+ lang = initialSourceLanguage(candidates: candidates, last: UserDefaults.standard.string(forKey: Pref.lastDetected),+ systemLanguages: Locale.preferredLanguages)+ target = Pref.target(for: lang.code)+ settled = candidates.count < 2+ detection.start()+ debugLog("room: auto candidates=\(candidates.map(\.locale)) start=\(lang.locale)")+ }if await Recognition.status(lang.locale) != .installed {status = L("正在下载 \(lang.name) 语音模型…")try await Recognition.install(lang.locale)@@ -156,29 +188,23 @@ final class RoomListen: ObservableObject {audio.onInterruption = { [weak self] began in self?.interrupted(began) }// 保存会议录音 off: nothing is written; voiceprints still read the last minute in memory.let keep = UserDefaults.standard.bool(forKey: Pref.recordAudio)- try audio.start(recognizer: stream, recording: keep ? AudioFileWriter.partial(store.systemAudioURL(s.id)) : nil)+ try audio.start(recognizer: stream, recording: keep ? AudioFileWriter.partial(store.systemAudioURL(s.id)) : nil,+ keep: !settled)heardVoice = falseaudio.onLevel = { [weak self] v inguard let self, !self.paused else { return }self.level = vif v > 0.55 {self.heardVoice = true+ self.lastVoiceAt = Date()if self.status == L("没听到声音,请拔掉耳机或调大音量") { self.status = "" }+ if !self.settled, self.status.isEmpty { self.status = L("正在识别语言…") }}}- reader = Task { [weak self] in- do {- for try await piece in stream.results { self?.handle(piece) }- } catch {- debugLog("room: recognizer ended: \(error)")- // The meeting so far is kept; listening stops with a reason rather than hearing nothing.- guard let self, self.isRunning else { return }- self.stop()- self.status = L("识别中断了,请重新开始听")- }- }+ read(stream)status = ""if speakerMode { watchSilence(s.id) }+ if !settled { watchLanguage() }debugLog("room: listening locale=\(lang.locale) target=\(target) speaker=\(speakerMode) format=\(stream.format) session=\(s.id)")onStateChange?()} catch {@@ -187,6 +213,119 @@ final class RoomListen: ObservableObject {}}+ private func read(_ stream: RecognitionStream) {+ generation += 1+ let gen = generation+ reader = Task { [weak self] in+ do {+ for try await piece in stream.results { self?.handle(piece, gen) }+ } catch {+ // A recognizer replaced by another language's ends as it should.+ guard let self, gen == self.generation else { return }+ debugLog("room: recognizer ended: \(error)")+ // The meeting so far is kept; listening stops with a reason rather than hearing nothing.+ guard self.isRunning else { return }+ self.stop()+ self.status = L("识别中断了,请重新开始听")+ }+ }+ }++ // MARK: 自动识别++ /// The models to compare: the two likeliest for this phone (downloaded if they aren't yet),+ /// then any other already here.+ private func autoCandidates() async -> [Lang] {+ let likely = likelySourceLanguages(last: UserDefaults.standard.string(forKey: Pref.lastDetected),+ systemLanguages: Locale.preferredLanguages).prefix(2)+ var out: [Lang] = []+ for lang in likely {+ if await Recognition.status(lang.locale) != .installed {+ status = L("正在下载 \(lang.name) 语音模型…")+ do { try await Recognition.install(lang.locale) } catch {+ debugLog("room: auto can't fetch \(lang.locale): \(error)")+ continue+ }+ }+ out.append(lang)+ }+ for lang in sourceLanguages where out.count < Self.maxCandidates && !out.contains(lang) {+ if await Recognition.status(lang.locale) == .installed { out.append(lang) }+ }+ return out+ }++ /// Checks the language each time a few more seconds of speech came in, until it is settled.+ private func watchLanguage() {+ detector?.cancel()+ detector = Task { [weak self] in+ var checkedAt = 0.0+ while !Task.isCancelled {+ try? await Task.sleep(nanoseconds: 1_000_000_000)+ guard let self, self.isRunning, !self.settled else { return }+ if self.paused { continue }+ let kept = self.audio.keptSeconds+ if kept > Self.giveUpSeconds {+ debugLog("room: auto gave up after \(Int(kept))s, staying in \(self.lang.locale)")+ self.settle()+ return+ }+ // Someone spoke just now, and enough of it since the last check to tell.+ guard kept >= 5, kept - checkedAt >= 4, Date().timeIntervalSince(self.lastVoiceAt) < 3 else { continue }+ checkedAt = kept+ let ranked = await LanguageDetector.rank(self.audio.keptClip(last: 8), candidates: self.candidates)+ guard self.isRunning, !self.settled else { return }+ debugLog("room: auto check " + ranked.map { String(format: "%@=%.2f", $0.lang.locale, $0.score) }.joined(separator: " "))+ switch self.detection.apply(ranked, active: self.lang) {+ case .confirmed:+ self.settle()+ case .switchTo(let other, _):+ await self.switchTo(other)+ default:+ // Too close to call twice: the language listened in stands.+ if self.detection.settledEnough { self.settle() }+ }+ }+ }+ }++ /// The language listened in is the one: the lines held come out.+ private func settle() {+ guard !settled else { return }+ settled = true+ audio.stopKeeping()+ UserDefaults.standard.set(lang.locale, forKey: Pref.lastDetected)+ if status == L("正在识别语言…") { status = "" }+ debugLog("room: auto settled on \(lang.locale), \(held.count) lines held")+ let pieces = held+ held = []+ for p in pieces { handle(p, generation) }+ onStateChange?()+ }++ /// Another language: a recognizer for it hears everything kept so far, then the microphone.+ private func switchTo(_ other: Lang) async {+ guard let next = try? await Recognition.start(other.locale, drafts: true, confidence: true) else {+ debugLog("room: auto can't start \(other.locale), staying in \(lang.locale)")+ settle()+ return+ }+ guard isRunning, !settled else { await next.cancel(); return }+ let old = stream+ lang = other+ target = Pref.target(for: other.code)+ held = []+ draft = ""+ draftTranslation = ""+ reader?.cancel()+ stream = next+ read(next)+ audio.replay(into: next)+ Task { await old?.cancel() }+ debugLog("room: auto switched to \(other.locale)")+ settle()+ }+/// Paused while the audio is taken, then on again by itself; if the system won't give the/// microphone back yet (the app is still behind a call screen), again when the app comes back.private func interrupted(_ began: Bool) {@@ -272,6 +411,11 @@ final class RoomListen: ObservableObject {/// `endedAt`: when the meeting really ended (结束会议 by itself: a little after the last words).func stop(endedAt: Date? = nil) {guard isRunning else { return }+ detector?.cancel()+ detector = nil+ // Ended before the language was settled: what was heard is kept, in the language listened in.+ if !settled, sessionID != nil { settle() }+ settled = trueisRunning = falsepaused = falseuserPaused = false@@ -297,7 +441,13 @@ final class RoomListen: ObservableObject {onStateChange?()}- private func handle(_ piece: Recognition.Piece) {+ private func handle(_ piece: Recognition.Piece, _ gen: Int) {+ guard gen == generation else { return }+ // 自动识别 not settled: a line in what may be the wrong language waits, and no draft shows.+ guard settled else {+ if piece.isFinal { held.append(piece) }+ return+ }let text = piece.text.trimmingCharacters(in: .whitespacesAndNewlines)guard piece.isFinal else {if text != draft {@@ -346,7 +496,7 @@ final class RoomListen: ObservableObject {// Half a minute apart, so two lines are never joined as one sentence a pause cut.silentClock += 30let at = silentClock- handle(Recognition.Piece(text: text, isFinal: true, start: at, end: at + 2, confidence: nil))+ handle(Recognition.Piece(text: text, isFinal: true, start: at, end: at + 2, confidence: nil), generation)}/// Debug (`heardT:<text>|<translation>`): as `debugHeard`, with the translation given, for@@ -410,7 +560,7 @@ final class RoomAudio: @unchecked Sendable {/// A new engine for each meeting: one restarted after `stop` hears only silence in the simulator.private var engine = AVAudioEngine()private let queue = DispatchQueue(label: "com.indaloop.cicada.room", qos: .userInitiated)- private let toRecognizer = PCMConverter()+ private var toRecognizer = PCMConverter()private let toVoice = PCMConverter()private let voiceFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16_000, channels: 1, interleaved: false)!private var stream: RecognitionStream?@@ -421,10 +571,54 @@ final class RoomAudio: @unchecked Sendable {private var ring: [Float] = []private var ringStart = 0.0private var lastLevel = Date.distantPast+ /// 自动识别: the 16 kHz audio since the start, until the language is settled.+ private var keeping = false+ private var kept: [AVAudioPCMBuffer] = []+ private var keptFrames = 0var fedSeconds: Double { queue.sync { fed } }+ var keptSeconds: Double { queue.sync { Double(keptFrames) / 16_000 } }++ /// The last `seconds` of the audio kept, for a language check.+ func keptClip(last seconds: Double) -> [AVAudioPCMBuffer] {+ queue.sync {+ var out: [AVAudioPCMBuffer] = [], frames = 0+ for b in kept.reversed() where Double(frames) < seconds * 16_000 {+ out.insert(b, at: 0)+ frames += Int(b.frameLength)+ }+ return out+ }+ }- func start(recognizer: RecognitionStream, recording: URL?) throws {+ func stopKeeping() {+ queue.sync {+ keeping = false+ kept = []+ keptFrames = 0+ }+ }++ /// Settled on another language: `recognizer` takes over and first hears everything kept, so+ /// nothing said before is lost and its clock runs from the meeting's start as the old one did.+ func replay(into recognizer: RecognitionStream) {+ queue.sync {+ stream = recognizer+ toRecognizer = PCMConverter()+ fed = 0+ let conv = PCMConverter()+ for b in kept {+ guard let c = conv.convert(b, to: recognizer.format) else { continue }+ recognizer.append(c)+ fed += Double(c.frameLength) / c.format.sampleRate+ }+ keeping = false+ kept = []+ keptFrames = 0+ }+ }++ func start(recognizer: RecognitionStream, recording: URL?, keep: Bool = false) throws {let session = AVAudioSession.sharedInstance()// .measurement: no voice processing, which would duck what the room says as "echo".// .defaultToSpeaker sends every app's sound to the speaker, not the earpiece, while we record.@@ -437,6 +631,9 @@ final class RoomAudio: @unchecked Sendable {fed = 0ring = []ringStart = 0+ keeping = keep+ kept = []+ keptFrames = 0}try tapAndStart()observe(session)@@ -516,6 +713,10 @@ final class RoomAudio: @unchecked Sendable {let n = Int(v.frameLength)if recorder == nil, let url = recordingURL { recorder = AudioFileWriter.open(url, format: voiceFormat) }try? recorder?.write(from: v)+ if keeping {+ kept.append(v)+ keptFrames += n+ }if voices {ring.append(contentsOf: UnsafeBufferPointer(start: p, count: n))let keep = 60 * 16_000diff --git a/ios/shared-sources.txt b/ios/shared-sources.txtindex 0410509..26aaa6a 100644--- a/ios/shared-sources.txt+++ b/ios/shared-sources.txt@@ -20,6 +20,7 @@ Sources/Cicada/Diagnostics.swiftSources/Cicada/RecordList.swiftSources/Cicada/Languages.swiftSources/Cicada/Recognition.swift+Sources/Cicada/LanguageDetector.swiftSources/Cicada/CloudHearing.swiftSources/Cicada/SoundKind.swiftSources/Cicada/SpeakerProfiles.swift