知了 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): first launch walks through the microphone, a sample meeting and the Ling key, and recordings or videos import from Files, Photos or the share sheet
wquguru81c5b19f29d4
diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.stringsindex e32d256..12f8514 100644--- a/Resources/en.lproj/Localizable.strings+++ b/Resources/en.lproj/Localizable.strings@@ -1544,3 +1544,37 @@"标记这个人叫什么" = "Name this person";"标记人名…" = "Name…";"记住这个声音…" = "Remember This Voice…";++/* iOS: first launch and import */+"第 %lld 步,共 3 步" = "Step %lld of 3";+"听会议室" = "Listen to the Room";+"用麦克风听,实时双语字幕和纪要" = "Listens with the microphone: live bilingual subtitles and notes";+"听会议室里的人说话" = "Hears the people in the room";+"%@语音模型" = "%@ Speech Model";+"在手机上把声音转成文字" = "Turns speech into text on this phone";+"已就绪" = "Ready";+"下载" = "Download";+"线上会议里的声音请用电脑版" = "For online meetings, use the Mac app";+"手机放出来,知了用麦克风听" = "The phone plays it, Cicada listens with the microphone";+"播放示例" = "Play Sample";+"放完了" = "Finished";+"约 %lld 秒" = "About %lld s";+"示例会议" = "Sample meeting";+"按 ▶ 开始,字幕会出现在这里" = "Press ▶ and subtitles appear here";+"没出字?把音量调大,手机别盖住" = "No text? Turn the volume up and keep the phone uncovered";+"跳过" = "Skip";+"听到了,继续" = "Heard It, Continue";+"key 只存在这台手机上,不进备份" = "The key stays on this phone and out of backups";+"纪要、改错和同声传译要用;不填也能看字幕" = "Needed for notes, fixes and interpreting; subtitles work without it";+"填入 Ling key" = "Add a Ling Key";+"没有 key?去 Ling 拿一个" = "No key? Get one from Ling";+"开始用知了" = "Start Using Cicada";+"以后再填" = "Later";+"正在导入" = "Importing";+"只能导入录音或带声音的视频" = "Only recordings or videos with sound can be imported";+"从文件导入" = "Import from Files";+"从相册导入视频" = "Import Video from Photos";+"这个视频读不出来" = "This video can't be read";+"切到别的 app 也会继续" = "Keeps going in other apps";+"还有 %lld 个文件在排队" = "%lld more files waiting";+"停止" = "Stop";diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.stringsindex 0adcda3..58ccfc7 100644--- a/Resources/ja.lproj/Localizable.strings+++ b/Resources/ja.lproj/Localizable.strings@@ -1544,3 +1544,37 @@"标记这个人叫什么" = "この人に名前を付ける";"标记人名…" = "名前を付ける…";"记住这个声音…" = "この声を覚える…";++/* iOS: first launch and import */+"第 %lld 步,共 3 步" = "ステップ %lld / 3";+"听会议室" = "会議室を聞く";+"用麦克风听,实时双语字幕和纪要" = "マイクで聞いて、2か国語の字幕と議事メモをリアルタイムで";+"听会议室里的人说话" = "会議室の人の話を聞きます";+"%@语音模型" = "%@の音声モデル";+"在手机上把声音转成文字" = "この端末で音声を文字にします";+"已就绪" = "準備完了";+"下载" = "ダウンロード";+"线上会议里的声音请用电脑版" = "オンライン会議の音声は Mac 版で";+"手机放出来,知了用麦克风听" = "端末から流して、Cicada がマイクで聞きます";+"播放示例" = "サンプルを再生";+"放完了" = "再生終了";+"约 %lld 秒" = "約 %lld 秒";+"示例会议" = "サンプル会議";+"按 ▶ 开始,字幕会出现在这里" = "▶ を押すと、ここに字幕が出ます";+"没出字?把音量调大,手机别盖住" = "文字が出ない?音量を上げて、端末をふさがないで";+"跳过" = "スキップ";+"听到了,继续" = "聞こえた、次へ";+"key 只存在这台手机上,不进备份" = "キーはこの端末だけに保存され、バックアップされません";+"纪要、改错和同声传译要用;不填也能看字幕" = "議事メモ・修正・同時通訳に使います。なくても字幕は出ます";+"填入 Ling key" = "Ling キーを入力";+"没有 key?去 Ling 拿一个" = "キーがない?Ling で取得";+"开始用知了" = "Cicada を使い始める";+"以后再填" = "あとで";+"正在导入" = "読み込み中";+"只能导入录音或带声音的视频" = "読み込めるのは録音か音声付きの動画だけです";+"从文件导入" = "ファイルから読み込む";+"从相册导入视频" = "写真から動画を読み込む";+"这个视频读不出来" = "この動画は読み込めません";+"切到别的 app 也会继续" = "ほかのアプリに切り替えても続きます";+"还有 %lld 个文件在排队" = "あと %lld 件が待機中";+"停止" = "停止";diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.stringsindex 3e8c3c1..a500664 100644--- a/Resources/ko.lproj/Localizable.strings+++ b/Resources/ko.lproj/Localizable.strings@@ -1544,3 +1544,37 @@"标记这个人叫什么" = "이 사람 이름 붙이기";"标记人名…" = "이름 붙이기…";"记住这个声音…" = "이 목소리 기억하기…";++/* iOS: first launch and import */+"第 %lld 步,共 3 步" = "3단계 중 %lld단계";+"听会议室" = "회의실 듣기";+"用麦克风听,实时双语字幕和纪要" = "마이크로 듣고, 실시간 이중 언어 자막과 회의록";+"听会议室里的人说话" = "회의실 사람들의 말을 듣습니다";+"%@语音模型" = "%@ 음성 모델";+"在手机上把声音转成文字" = "이 기기에서 음성을 텍스트로 바꿉니다";+"已就绪" = "준비됨";+"下载" = "다운로드";+"线上会议里的声音请用电脑版" = "온라인 회의 소리는 Mac 앱으로";+"手机放出来,知了用麦克风听" = "휴대폰이 재생하고 Cicada가 마이크로 듣습니다";+"播放示例" = "샘플 재생";+"放完了" = "재생 끝";+"约 %lld 秒" = "약 %lld초";+"示例会议" = "샘플 회의";+"按 ▶ 开始,字幕会出现在这里" = "▶을 누르면 여기에 자막이 나옵니다";+"没出字?把音量调大,手机别盖住" = "글자가 안 나오면 볼륨을 높이고 휴대폰을 가리지 마세요";+"跳过" = "건너뛰기";+"听到了,继续" = "들렸어요, 계속";+"key 只存在这台手机上,不进备份" = "키는 이 휴대폰에만 저장되고 백업되지 않습니다";+"纪要、改错和同声传译要用;不填也能看字幕" = "회의록·수정·통역에 필요합니다. 없어도 자막은 나옵니다";+"填入 Ling key" = "Ling 키 입력";+"没有 key?去 Ling 拿一个" = "키가 없나요? Ling에서 받기";+"开始用知了" = "Cicada 시작하기";+"以后再填" = "나중에";+"正在导入" = "가져오는 중";+"只能导入录音或带声音的视频" = "녹음이나 소리가 있는 동영상만 가져올 수 있습니다";+"从文件导入" = "파일에서 가져오기";+"从相册导入视频" = "사진에서 동영상 가져오기";+"这个视频读不出来" = "이 동영상을 읽을 수 없습니다";+"切到别的 app 也会继续" = "다른 앱으로 전환해도 계속됩니다";+"还有 %lld 个文件在排队" = "%lld개 파일 대기 중";+"停止" = "중지";diff --git a/Resources/zh-Hans.lproj/Localizable.strings b/Resources/zh-Hans.lproj/Localizable.stringsindex 236e2ad..f2c4c48 100644--- a/Resources/zh-Hans.lproj/Localizable.strings+++ b/Resources/zh-Hans.lproj/Localizable.strings@@ -1449,3 +1449,37 @@"标记这个人叫什么" = "标记这个人叫什么";"标记人名…" = "标记人名…";"记住这个声音…" = "记住这个声音…";++/* iOS: first launch and import */+"第 %lld 步,共 3 步" = "第 %lld 步,共 3 步";+"听会议室" = "听会议室";+"用麦克风听,实时双语字幕和纪要" = "用麦克风听,实时双语字幕和纪要";+"听会议室里的人说话" = "听会议室里的人说话";+"%@语音模型" = "%@语音模型";+"在手机上把声音转成文字" = "在手机上把声音转成文字";+"已就绪" = "已就绪";+"下载" = "下载";+"线上会议里的声音请用电脑版" = "线上会议里的声音请用电脑版";+"手机放出来,知了用麦克风听" = "手机放出来,知了用麦克风听";+"播放示例" = "播放示例";+"放完了" = "放完了";+"约 %lld 秒" = "约 %lld 秒";+"示例会议" = "示例会议";+"按 ▶ 开始,字幕会出现在这里" = "按 ▶ 开始,字幕会出现在这里";+"没出字?把音量调大,手机别盖住" = "没出字?把音量调大,手机别盖住";+"跳过" = "跳过";+"听到了,继续" = "听到了,继续";+"key 只存在这台手机上,不进备份" = "key 只存在这台手机上,不进备份";+"纪要、改错和同声传译要用;不填也能看字幕" = "纪要、改错和同声传译要用;不填也能看字幕";+"填入 Ling key" = "填入 Ling key";+"没有 key?去 Ling 拿一个" = "没有 key?去 Ling 拿一个";+"开始用知了" = "开始用知了";+"以后再填" = "以后再填";+"正在导入" = "正在导入";+"只能导入录音或带声音的视频" = "只能导入录音或带声音的视频";+"从文件导入" = "从文件导入";+"从相册导入视频" = "从相册导入视频";+"这个视频读不出来" = "这个视频读不出来";+"切到别的 app 也会继续" = "切到别的 app 也会继续";+"还有 %lld 个文件在排队" = "还有 %lld 个文件在排队";+"停止" = "停止";diff --git a/ios/Resources/Info.plist b/ios/Resources/Info.plistindex 644340b..bf66478 100644--- a/ios/Resources/Info.plist+++ b/ios/Resources/Info.plist@@ -51,6 +51,28 @@<array><string>audio</string></array>+ <key>BGTaskSchedulerPermittedIdentifiers</key>+ <array>+ <string>com.wquguru.cicada.import</string>+ </array>+ <key>CFBundleDocumentTypes</key>+ <array>+ <dict>+ <key>CFBundleTypeName</key>+ <string>Audio or video</string>+ <key>CFBundleTypeRole</key>+ <string>Viewer</string>+ <key>LSHandlerRank</key>+ <string>Alternate</string>+ <key>LSItemContentTypes</key>+ <array>+ <string>public.audio</string>+ <string>public.movie</string>+ </array>+ </dict>+ </array>+ <key>LSSupportsOpeningDocumentsInPlace</key>+ <false/><key>UILaunchScreen</key><dict/><key>UIApplicationSupportsIndirectInputEvents</key>diff --git a/ios/Sources/Cicada/CicadaApp.swift b/ios/Sources/Cicada/CicadaApp.swiftindex 54705c5..0870eea 100644--- a/ios/Sources/Cicada/CicadaApp.swift+++ b/ios/Sources/Cicada/CicadaApp.swift@@ -5,6 +5,8 @@ import SwiftUIstruct CicadaApp: App {@StateObject private var model = AppModel()+ init() { ImportBackground.register() }+var body: some Scene {WindowGroup {RootView()@@ -12,7 +14,7 @@ struct CicadaApp: App {.environmentObject(model.ling).environmentObject(model.notes).environmentObject(model.room)- .onOpenURL { model.open($0) }+ .onOpenURL { if !model.openedFile($0) { model.open($0) } }.onReceive(NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)) { _ inmodel.room.appBecameActive()}@@ -40,6 +42,8 @@ enum Pref {static let askNames = "askNames"/// 声音来源 (iOS only): "room", people at the table, or "speaker", video this phone plays aloud.static let hear = "iosHear"+ /// 第一次打开's three steps are done (or skipped).+ static let welcomed = "iosWelcomed"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.@@ -92,6 +96,20 @@ final class AppModel: ObservableObject {}return r}()+ /// 导入录音或视频: the Mac's importer, with the iOS app's languages.+ let importPrefs = ImportPrefs()+ lazy var importer: FileImporter = {+ let i = FileImporter(store: store, settings: importPrefs, translator: translator, profiles: nil)+ // As on the Mac: a file transcribed to the end gets its notes when there is a key.+ i.onFinished = { [weak self] id in+ guard let self, self.ling.hasKey else { return }+ self.notes.generate(for: id)+ }+ ImportBackground.importer = i+ return i+ }()+ /// Why a picked file wasn't imported.+ @Published var importProblem: String?let pip = PiPSubtitles()private var roomWatch: AnyCancellable?let liveActivity = LiveActivityController()@@ -126,6 +144,9 @@ final class AppModel: ObservableObject {@Published var editingWord: String?@Published var deletedWord: DeletedWord?@Published var wordConflict: WordConflict?+ /// 第一次打开 (Welcome.swift) and its step.+ @Published var showWelcome = !UserDefaults.standard.bool(forKey: Pref.welcomed)+ @Published var welcomeStep = 0/// Dev only: the iPad window size `window:` lays the app out at (DevWindow in Debug.swift).@Published var devWindow: CGSize?@@ -244,6 +265,8 @@ final class AppModel: ObservableObject {}func deleteSession(_ id: String) {+ importer.cancel(id)+ ImportFiles.remove(store.session(id)?.sourcePath)if selection == id { selection = nil }searchPath.removeAll { $0 == id }if speakerUndo?.session == id { speakerUndo = nil }diff --git a/ios/Sources/Cicada/Debug.swift b/ios/Sources/Cicada/Debug.swiftindex 3b4cda2..92364e9 100644--- a/ios/Sources/Cicada/Debug.swift+++ b/ios/Sources/Cicada/Debug.swift@@ -62,9 +62,20 @@ extension AppModel {debugLog("window: \(arg) \(devWindow.map { "\($0)" } ?? "screen")")case "stop":stopListening()+ case "welcome":+ // welcome:<0|1|2> opens 第一次打开 at that step; welcome:done closes it as 开始用知了 does+ if arg == "done" { finishWelcome() } else { welcomeStep = Int(arg) ?? 0; showWelcome = true }+ case "samplePlay":+ welcomeStep = 1+ showWelcome = true+ playSample()+ case "sampleStop":+ stopSample()case "import":- // What the import button shows until M3.- comingSoon = L("导入录音或视频")+ // import:<path>[|<path>…], a file on the Mac the simulator runs on, as if picked in Files+ importFiles(arg.split(separator: "|").map { URL(fileURLWithPath: String($0)) })+ case "importStop":+ if let id = importer.current?.id { importer.cancel(id) }case "hear":// hear:room|speaker, 声音来源UserDefaults.standard.set(arg == "speaker" ? "speaker" : "room", forKey: Pref.hear)@@ -228,6 +239,8 @@ extension AppModel {if p.count == 2, let t = vocabulary.terms.first(where: { $0.word == p[0] }) { addHeard(p[1], to: t) }case "wordDelete":if let t = vocabulary.terms.first(where: { $0.word == arg }) { deleteWord(t) }+ case "importState":+ debugLog("import busy=\(importer.busy) phase=\(importer.phase) progress=\(String(format: "%.2f", importer.progress)) queue=\(importer.queue.count) current=\(importer.current?.id ?? "-")")case "state":debugLog("room running=\(room.isRunning) lines=\(room.lines.count) draft=\(room.draft.count) level=\(room.level) status=\(room.status) speaker=\(room.speakerMode) paused=\(room.paused) pip=\(pip.isActive) session=\(room.sessionID ?? "-")")debugLog("state tab=\(tab.rawValue) selection=\(selection ?? "-") page=\(recordPage) sessions=\(store.sessions.count) query=\(query) notesLang=\(notesLanguageCode(selection ?? store.sessions.first?.id ?? "")) undo=\(speakerUndo?.text ?? "-")")diff --git a/ios/Sources/Cicada/Importing.swift b/ios/Sources/Cicada/Importing.swiftnew file mode 100644index 0000000..b3f3eb1--- /dev/null+++ b/ios/Sources/Cicada/Importing.swift@@ -0,0 +1,235 @@+import BackgroundTasks+import CoreTransferable+import PhotosUI+import SwiftUI+import UniformTypeIdentifiers++// 导入录音或视频: the Mac's FileImporter, fed from Files, Photos or another app's share sheet. Each+// file is copied into the app first (a picked file's access ends with the picker, and Photos hands+// over a temporary copy), and the copy is the record's source. While files are turning into+// 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.+@MainActor+final class ImportPrefs: ImportSettings {+ var importLanguage: String { Pref.sourceLang.locale }+ var speakerVoices: Bool { UserDefaults.standard.bool(forKey: Pref.voices) }+ func resolvedTarget(source: String?) -> String {+ UserDefaults.standard.string(forKey: Pref.target).flatMap { $0 == "system" ? nil : $0 }+ ?? followSystemTarget(source: source, systemLanguages: Locale.preferredLanguages)+ }+}++enum ImportFiles {+ /// The app's own copies of imported files.+ static var folder: URL {+ FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ .appendingPathComponent(DevBuild.supportFolder).appendingPathComponent("Imports")+ }++ /// A copy under `folder`, keeping the file's name (it becomes the record's title).+ static func copy(_ url: URL) -> URL? {+ let access = url.startAccessingSecurityScopedResource()+ defer { if access { url.stopAccessingSecurityScopedResource() } }+ let dir = folder.appendingPathComponent(UUID().uuidString)+ let out = dir.appendingPathComponent(url.lastPathComponent)+ do {+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ try FileManager.default.copyItem(at: url, to: out)+ return out+ } catch {+ debugLog("import: can't copy the file: \(error)")+ return nil+ }+ }++ /// The copy goes with its record.+ static func remove(_ path: String?) {+ guard let path, path.hasPrefix(folder.path) else { return }+ try? FileManager.default.removeItem(at: URL(fileURLWithPath: path).deletingLastPathComponent())+ }+}++/// A video from Photos, as a file.+struct PickedMovie: Transferable {+ let url: URL++ static var transferRepresentation: some TransferRepresentation {+ FileRepresentation(contentType: .movie) { SentTransferredFile($0.url) } importing: { received in+ // The received file is gone after this returns: our own copy is what is imported.+ guard let copy = ImportFiles.copy(received.file) else { throw CocoaError(.fileWriteUnknown) }+ return PickedMovie(url: copy)+ }+ }+}++/// The system's progress for imports running behind other apps (iOS 26).+@MainActor+enum ImportBackground {+ static var identifier: String { (Bundle.main.bundleIdentifier ?? "com.wquguru.cicada") + ".import" }+ private static var task: BGContinuedProcessingTask?+ private static var ticker: Timer?+ static weak var importer: FileImporter?++ /// Before the app finishes launching, as BGTaskScheduler requires.+ static func register() {+ let ok = BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: .main) { t in+ MainActor.assumeIsolated { run(t) }+ }+ debugLog("import: background task registered=\(ok)")+ }++ static func begin(_ title: String) {+ guard task == nil else { return }+ let request = BGContinuedProcessingTaskRequest(identifier: identifier, title: L("正在导入"), subtitle: title)+ request.strategy = .queue+ do {+ try BGTaskScheduler.shared.submit(request)+ } catch {+ debugLog("import: background task not submitted: \(error)")+ }+ }++ private static func run(_ t: BGTask) {+ guard let t = t as? BGContinuedProcessingTask else { t.setTaskCompleted(success: false); return }+ task = t+ t.progress.totalUnitCount = 1000+ t.expirationHandler = {+ // The system wants the time back: what was transcribed stays, the record offers 重新转写.+ MainActor.assumeIsolated {+ debugLog("import: background time expired")+ importer?.cancelAll()+ finish(success: false)+ }+ }+ ticker = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { _ in+ MainActor.assumeIsolated {+ guard let importer, let task else { return }+ if !importer.busy { finish(success: true); return }+ task.progress.completedUnitCount = Int64(importer.progress * 1000)+ if let id = importer.current?.id, let s = importer.store.session(id) {+ task.updateTitle(L("正在导入"), subtitle: s.displayTitle)+ }+ }+ }+ debugLog("import: running in the background")+ }++ private static func finish(success: Bool) {+ ticker?.invalidate()+ ticker = nil+ task?.setTaskCompleted(success: success)+ task = nil+ }+}++extension AppModel {+ /// Files from the picker, Photos or the share sheet: copied, then queued as records.+ func importFiles(_ urls: [URL], copied: Bool = false) {+ let files = urls.filter(FileImporter.importable).compactMap { copied ? $0 : ImportFiles.copy($0) }+ guard !files.isEmpty else {+ if !urls.isEmpty { importProblem = L("只能导入录音或带声音的视频") }+ return+ }+ Task {+ let ids = await importer.add(files)+ debugLog("import: added \(ids.count) files")+ ImportBackground.begin(files[0].deletingPathExtension().lastPathComponent)+ }+ }++ /// A file shared to the app ("用知了打开"): it arrives in the app's Inbox, already a copy.+ func openedFile(_ url: URL) -> Bool {+ guard url.isFileURL else { return false }+ importFiles([url])+ try? FileManager.default.removeItem(at: url)+ return true+ }+}++/// The import button's two sources.+struct ImportMenu<Label: View>: View {+ @EnvironmentObject var model: AppModel+ @State private var files = false+ @State private var photo: PhotosPickerItem?+ @State private var photos = false+ @ViewBuilder var label: Label++ var body: some View {+ Menu {+ Button { files = true } label: { SwiftUI.Label("从文件导入", systemImage: "folder") }+ Button { photos = true } label: { SwiftUI.Label("从相册导入视频", systemImage: "photo.on.rectangle") }+ } label: { label }+ .accessibilityLabel(Text("导入录音或视频"))+ .fileImporter(isPresented: $files, allowedContentTypes: [.audio, .movie, .audiovisualContent], allowsMultipleSelection: true) { result in+ if case .success(let urls) = result { model.importFiles(urls) }+ }+ .photosPicker(isPresented: $photos, selection: $photo, matching: .videos)+ .onChange(of: photo) {+ guard let item = photo else { return }+ photo = nil+ Task {+ do {+ if let movie = try await item.loadTransferable(type: PickedMovie.self) { model.importFiles([movie.url], copied: true) }+ } catch {+ debugLog("import: Photos video failed: \(error)")+ model.importProblem = L("这个视频读不出来")+ }+ }+ }+ }+}++/// 正在导入, at the top of the records while files are turning into records: the file, how far+/// it has got, and 停止.+struct ImportCard: View {+ @EnvironmentObject var model: AppModel+ @ObservedObject var importer: FileImporter++ var body: some View {+ if let job = importer.current {+ VStack(alignment: .leading, spacing: 0) {+ SectionLabel(text: L("正在导入"))+ Card {+ VStack(alignment: .leading, spacing: 10) {+ HStack(spacing: 10) {+ Image(systemName: job.url.pathExtension.lowercased().isVideo ? "film" : "waveform")+ .font(.system(size: 18)).foregroundStyle(Ink.ink).frame(width: 24)+ VStack(alignment: .leading, spacing: 1) {+ Text(verbatim: job.url.lastPathComponent).font(.body.weight(.semibold)).foregroundStyle(Ink.ink).lineLimit(1)+ Text(phase).font(.footnote).foregroundStyle(Ink.secondary).lineLimit(1).monospacedDigit()+ }+ Spacer(minLength: 8)+ Button { importer.cancel(job.id) } label: {+ Text("停止").font(.subheadline).foregroundStyle(Ink.ink)+ .padding(.horizontal, 12).frame(minHeight: 32)+ .background(Ink.ground, in: Capsule())+ }+ .buttonStyle(.plain)+ .frame(minHeight: 44)+ }+ ProgressView(value: importer.progress).tint(Ink.ink)+ Text(importer.queue.isEmpty ? L("切到别的 app 也会继续") : L("还有 \(importer.queue.count) 个文件在排队"))+ .font(.footnote).foregroundStyle(Ink.tertiary)+ }+ .padding(16)+ }+ }+ }+ }++ private var phase: String {+ switch importer.phase {+ case .preparing: L("正在读取文件…")+ case .detecting: L("正在听是哪种语言…")+ case .downloading(let name): L("正在下载 \(name) 语音模型…")+ case .transcribing: L("文字记录已转到 \(TranscriptExport.clock(importer.heard)) / \(TranscriptExport.clock(importer.duration))")+ case .translating: L("还有 \(importer.untranslated) 句在翻译")+ }+ }+}++private extension String {+ var isVideo: Bool { UTType(filenameExtension: self)?.conforms(to: .movie) ?? false }+}diff --git a/ios/Sources/Cicada/RecordsView.swift b/ios/Sources/Cicada/RecordsView.swiftindex 9a2ee0f..774c56c 100644--- a/ios/Sources/Cicada/RecordsView.swift+++ b/ios/Sources/Cicada/RecordsView.swift@@ -22,11 +22,10 @@ struct RecordsSplit: View {ScrollView {VStack(alignment: .leading, spacing: 0) {HomeTitle(trailing: AnyView(- Button { model.comingSoon = L("导入录音或视频") } label: { GlassIcon(systemName: "arrow.down.to.line") }- .buttonStyle(.plain)- .accessibilityLabel(Text("导入录音或视频"))))+ ImportMenu { GlassIcon(systemName: "arrow.down.to.line") })).padding(.top, 6)ListenBar().padding(.top, 16)+ ImportCard(importer: model.importer)if store.sessions.isEmpty {EmptyRecords().frame(maxWidth: .infinity).padding(.top, 40)} else {@@ -98,13 +97,13 @@ struct PadRoot: View {private var sidebar: some View {VStack(alignment: .leading, spacing: 0) {HomeTitle(logo: 48, titleSize: 26, trailing: AnyView(HStack(spacing: 0) {- Button { model.comingSoon = L("导入录音或视频") } label: { PadIcon(systemName: "arrow.down.to.line") }- .buttonStyle(.plain).accessibilityLabel(Text("导入录音或视频"))+ ImportMenu { PadIcon(systemName: "arrow.down.to.line") }Button { model.showSettings = true } label: { PadIcon(systemName: "gearshape") }.buttonStyle(.plain).accessibilityLabel(Text("设置"))})).padding(.horizontal, 4)ListenBar(onGlass: true).padding(.top, 14).padding(.bottom, 12)+ ImportCard(importer: model.importer).padding(.top, -22).padding(.bottom, 12)HStack(spacing: 8) {Image(systemName: "magnifyingglass").foregroundStyle(Ink.secondary)TextField(text: $model.query) { Text("搜索文字记录") }diff --git a/ios/Sources/Cicada/RootView.swift b/ios/Sources/Cicada/RootView.swiftindex b9d30f5..3009a94 100644--- a/ios/Sources/Cicada/RootView.swift+++ b/ios/Sources/Cicada/RootView.swift@@ -19,6 +19,11 @@ struct RootView: View {.tint(Ink.accent)// The Mac's palette is light only (Palette in Views.swift); a dark one comes later, for both..preferredColorScheme(.light)+ .fullScreenCover(isPresented: $model.showWelcome) { Welcome().environmentObject(model).environmentObject(model.ling).environmentObject(model.room) }+ .alert(Text(model.importProblem ?? ""), isPresented: Binding(get: { model.importProblem != nil },+ set: { if !$0 { model.importProblem = nil } })) {+ Button("好") { model.importProblem = nil }+ }.alert(Text(model.comingSoon ?? ""), isPresented: Binding(get: { model.comingSoon != nil },set: { if !$0 { model.comingSoon = nil } })) {Button("好") { model.comingSoon = nil }diff --git a/ios/Sources/Cicada/Welcome.swift b/ios/Sources/Cicada/Welcome.swiftnew file mode 100644index 0000000..fbe7194--- /dev/null+++ b/ios/Sources/Cicada/Welcome.swift@@ -0,0 +1,458 @@+import AVFoundation+import SwiftUI++// 第一次打开: three steps, as the design canvas (知了 iOS M2–M4). iPhone can't hear other apps or+// speak into them, so the Mac's system-audio and BlackHole steps have no place here: the microphone+// and the speech model, a sample meeting played aloud, then the Ling key.++struct Welcome: View {+ @EnvironmentObject var model: AppModel++ var body: some View {+ VStack(spacing: 0) {+ Dots(step: model.welcomeStep).padding(.top, 18)+ Group {+ switch model.welcomeStep {+ case 0: WelcomeListen()+ case 1: WelcomeSample()+ default: WelcomeKey()+ }+ }+ .frame(maxWidth: 480)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ }+ .padding(.horizontal, 20)+ .padding(.bottom, 12)+ .background(Ink.ground.ignoresSafeArea())+ .tint(Ink.accent)+ .preferredColorScheme(.light)+ .animation(.snappy(duration: 0.25), value: model.welcomeStep)+ }+}++/// Where the user is: the current step a short bar, the others dots.+private struct Dots: View {+ let step: Int++ var body: some View {+ HStack(spacing: 6) {+ ForEach(0..<3, id: \.self) { i in+ Capsule().fill(i == step ? Ink.ink : Color(hex: 0xC9CCD3))+ .frame(width: i == step ? 22 : 6, height: 6)+ }+ }+ .accessibilityElement()+ .accessibilityLabel(Text(L("第 \(step + 1) 步,共 3 步")))+ }+}++/// The black capsule every step ends on.+struct PrimaryButton: View {+ let title: String+ var enabled = true+ let action: () -> Void++ var body: some View {+ Button(action: action) {+ Text(title).font(.headline).foregroundStyle(.white)+ .frame(maxWidth: .infinity, minHeight: 54)+ .background(enabled ? Ink.ink : Ink.tertiary, in: Capsule())+ .contentShape(Capsule())+ }+ .buttonStyle(.plain)+ .disabled(!enabled)+ }+}++// MARK: Step 1: the microphone and the speech model++private struct WelcomeListen: View {+ @EnvironmentObject var model: AppModel+ @State private var mic = AVAudioApplication.shared.recordPermission+ @State private var speech: ModelState = .unknown++ enum ModelState: Equatable { case unknown, ready, missing, downloading, failed }++ var body: some View {+ VStack(spacing: 22) {+ VStack(spacing: 12) {+ Logo(size: 72)+ Text("听会议室").font(.system(size: 28, weight: .bold)).foregroundStyle(Ink.ink)+ Text("用麦克风听,实时双语字幕和纪要").font(.subheadline).foregroundStyle(Ink.secondary)+ .multilineTextAlignment(.center)+ }+ .padding(.top, 28)+ Card {+ row(icon: "mic", title: L("麦克风"), detail: L("听会议室里的人说话")) { micState }+ Hairline(inset: 54)+ row(icon: "text.alignleft", title: L("\(Pref.name(of: Pref.sourceLang))语音模型"), detail: L("在手机上把声音转成文字")) { speechState }+ }+ Spacer(minLength: 0)+ VStack(spacing: 10) {+ PrimaryButton(title: L("继续")) { model.welcomeStep = 1 }+ Text("线上会议里的声音请用电脑版").font(.footnote).foregroundStyle(Ink.tertiary)+ }+ }+ .task { await refreshSpeech() }+ }++ private func row<V: View>(icon: String, title: String, detail: String, @ViewBuilder trailing: () -> V) -> some View {+ HStack(spacing: 12) {+ Image(systemName: icon).font(.system(size: 19)).foregroundStyle(Ink.ink).frame(width: 26)+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.body).foregroundStyle(Ink.ink)+ Text(detail).font(.footnote).foregroundStyle(Ink.secondary)+ }+ Spacer(minLength: 8)+ trailing()+ }+ .padding(.horizontal, 16).padding(.vertical, 12)+ .frame(minHeight: 60)+ }++ @ViewBuilder private var micState: some View {+ switch mic {+ case .granted: Done(text: L("已允许"))+ case .denied:+ SmallButton(title: L("去设置")) {+ if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(url) }+ }+ default:+ SmallButton(title: L("允许")) {+ Task {+ _ = await AVAudioApplication.requestRecordPermission()+ mic = AVAudioApplication.shared.recordPermission+ debugLog("welcome: microphone \(mic == .granted ? "granted" : "denied")")+ }+ }+ }+ }++ @ViewBuilder private var speechState: some View {+ switch speech {+ case .ready: Done(text: L("已就绪"))+ case .downloading: ProgressView().controlSize(.small)+ case .unknown: EmptyView()+ case .missing, .failed:+ SmallButton(title: speech == .failed ? L("重试") : L("下载")) {+ speech = .downloading+ Task {+ do {+ try await Recognition.install(Pref.sourceLang.locale)+ speech = .ready+ } catch {+ debugLog("welcome: model download failed: \(error)")+ speech = .failed+ }+ }+ }+ }+ }++ private func refreshSpeech() async {+ speech = await Recognition.status(Pref.sourceLang.locale) == .installed ? .ready : .missing+ }+}++private struct Done: View {+ let text: String++ var body: some View {+ HStack(spacing: 5) {+ Circle().fill(Ink.ok).frame(width: 7, height: 7)+ Text(text).font(.subheadline.weight(.semibold)).foregroundStyle(Ink.ok)+ }+ }+}++private struct SmallButton: View {+ let title: String+ let action: () -> Void++ var body: some View {+ Button(action: action) {+ Text(title).font(.subheadline.weight(.semibold)).foregroundStyle(Ink.ink)+ .padding(.horizontal, 16).frame(minHeight: 34)+ .background(Ink.ground, in: Capsule())+ .contentShape(Capsule())+ }+ .buttonStyle(.plain)+ .frame(minHeight: 44)+ }+}++// MARK: Step 2: the sample meeting, played aloud and heard through the microphone++private struct WelcomeSample: View {+ @EnvironmentObject var model: AppModel+ @EnvironmentObject var room: RoomListen+ @ObservedObject var sample: SampleRun++ init() { sample = SampleRun.shared }++ var body: some View {+ VStack(alignment: .leading, spacing: 20) {+ VStack(alignment: .leading, spacing: 6) {+ Text("先听一段示例").font(.system(size: 28, weight: .bold)).foregroundStyle(Ink.ink)+ Text("手机放出来,知了用麦克风听").font(.subheadline).foregroundStyle(Ink.secondary)+ }+ .padding(.horizontal, 4).padding(.top, 28)+ Card {+ HStack(spacing: 12) {+ VStack(alignment: .leading, spacing: 2) {+ if room.isRunning {+ TimelineView(.periodic(from: .now, by: 1)) { _ in+ HStack(spacing: 6) {+ LiveDot()+ Text(L("正在听 · \(TranscriptExport.clock(room.elapsed))"))+ }+ .font(.footnote.weight(.semibold).monospacedDigit()).foregroundStyle(Ink.accentText)+ }+ } else {+ Text(sample.played ? L("放完了") : L("约 \(Int(SampleRun.duration.rounded())) 秒")).font(.footnote).foregroundStyle(Ink.secondary)+ }+ Text(verbatim: L("示例会议") + " · " + Pref.pairText("en", Pref.targetCode)).font(.headline).foregroundStyle(Ink.ink)+ }+ Spacer(minLength: 8)+ Button { sample.playing ? model.stopSample() : model.playSample() } label: {+ Image(systemName: sample.playing ? "stop.fill" : "play.fill")+ .font(.system(size: 17, weight: .semibold))+ .foregroundStyle(sample.playing ? Ink.ink : .white)+ .frame(width: 46, height: 46)+ .background(sample.playing ? Ink.ground : Ink.accent, in: Circle())+ }+ .buttonStyle(.plain)+ .accessibilityLabel(sample.playing ? Text("停止") : Text("播放示例"))+ }+ .padding(.leading, 18).padding(.trailing, 10).padding(.vertical, 10)+ if sample.playing {+ GeometryReader { g in+ Capsule().fill(Ink.accent).frame(width: g.size.width * sample.progress, height: 3)+ }+ .frame(height: 3)+ .padding(.horizontal, 18).padding(.bottom, 10)+ }+ }+ Card {+ ScrollViewReader { proxy in+ ScrollView {+ VStack(alignment: .leading, spacing: 16) {+ if room.lines.isEmpty && room.draft.isEmpty {+ Text(room.status.isEmpty ? L("按 ▶ 开始,字幕会出现在这里") : room.status)+ .font(.subheadline).foregroundStyle(Ink.secondary)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ ForEach(room.lines.suffix(6)) { l in+ SampleLine(src: l.src, dst: l.dst ?? "", voice: l.voice, final: true)+ }+ if !room.draft.isEmpty {+ SampleLine(src: room.draft, dst: room.draftTranslation, voice: nil, final: false).id("draft")+ }+ Color.clear.frame(height: 1).id("end")+ }+ .padding(18)+ }+ .onChange(of: room.lines.count) { proxy.scrollTo("end", anchor: .bottom) }+ .onChange(of: room.draft) { proxy.scrollTo("end", anchor: .bottom) }+ }+ }+ .frame(maxHeight: .infinity)+ VStack(spacing: 10) {+ PrimaryButton(title: room.lines.isEmpty ? L("跳过") : L("听到了,继续")) {+ model.stopSample()+ model.welcomeStep = 2+ }+ Text("没出字?把音量调大,手机别盖住").font(.footnote).foregroundStyle(Ink.tertiary)+ .frame(maxWidth: .infinity)+ }+ }+ .onDisappear { model.stopSample() }+ }+}++private struct SampleLine: View {+ let src: String+ let dst: String+ let voice: Int?+ let final: Bool++ var body: some View {+ VStack(alignment: .leading, spacing: 4) {+ if let voice {+ Text(L("说话人 \(voice + 1)")).font(.caption.weight(.semibold))+ .foregroundStyle(SpeakerInk.ink(voice + 1))+ .padding(.horizontal, 8).padding(.vertical, 3)+ .background(SpeakerInk.tint(voice + 1), in: Capsule())+ }+ Text(verbatim: src).font(.subheadline).foregroundStyle(Ink.secondary)+ if !dst.isEmpty {+ Text(verbatim: dst).font(.body.weight(.semibold)).foregroundStyle(final ? Ink.ink : Ink.tertiary)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+}++/// sample.m4a through the speaker while the microphone listens: the room pipeline end to end.+@MainActor+final class SampleRun: NSObject, ObservableObject, AVAudioPlayerDelegate {+ static let shared = SampleRun()+ static let duration: Double = Bundle.main.url(forResource: "sample", withExtension: "m4a")+ .flatMap { try? AVAudioPlayer(contentsOf: $0) }?.duration ?? 0+ @Published private(set) var playing = false+ @Published private(set) var played = false+ @Published private(set) var progress = 0.0+ private var player: AVAudioPlayer?+ private var ticker: Timer?+ var onFinished: (() -> Void)?++ func play() {+ guard !playing, let url = Bundle.main.url(forResource: "sample", withExtension: "m4a"),+ let p = try? AVAudioPlayer(contentsOf: url) else { return }+ player = p+ p.delegate = self+ p.volume = 1+ p.play()+ playing = true+ progress = 0+ ticker = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] _ in+ MainActor.assumeIsolated {+ guard let self, let p = self.player, p.duration > 0 else { return }+ self.progress = p.currentTime / p.duration+ }+ }+ debugLog("sample: playing \(Int(p.duration)) s")+ }++ func stop() {+ guard playing else { return }+ player?.stop()+ finish()+ }++ private func finish() {+ ticker?.invalidate()+ ticker = nil+ player = nil+ playing = false+ played = true+ progress = 1+ onFinished?()+ }++ nonisolated func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {+ MainActor.assumeIsolated {+ debugLog("sample: finished")+ finish()+ }+ }+}++// MARK: Step 3: the Ling key++private struct WelcomeKey: View {+ @EnvironmentObject var model: AppModel+ @EnvironmentObject var ling: LingClient+ @State private var draft = ""++ var body: some View {+ VStack(alignment: .leading, spacing: 20) {+ VStack(alignment: .leading, spacing: 6) {+ Text(verbatim: L("填入 Ling key")).font(.system(size: 28, weight: .bold)).foregroundStyle(Ink.ink)+ Text("纪要、改错和同声传译要用;不填也能看字幕").font(.subheadline).foregroundStyle(Ink.secondary)+ }+ .padding(.horizontal, 4).padding(.top, 28)+ Card {+ VStack(alignment: .leading, spacing: 12) {+ Text(verbatim: "API key").font(.footnote).foregroundStyle(Ink.secondary)+ HStack(spacing: 8) {+ Group {+ if let key = ling.key {+ Text(verbatim: AIKey.masked(key)).frame(maxWidth: .infinity, alignment: .leading)+ } else {+ SecureField(text: $draft) { Text(verbatim: "sk-…") }+ .textInputAutocapitalization(.never)+ .autocorrectionDisabled()+ .submitLabel(.done)+ .onSubmit { save(draft) }+ }+ }+ .font(.body.monospaced())+ .padding(.horizontal, 12).frame(minHeight: 46)+ .background(Color(hex: 0xF9FAFB), in: RoundedRectangle(cornerRadius: 14, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 14, style: .continuous).stroke(Ink.line))+ Button { save(UIPasteboard.general.string ?? "") } label: {+ Text(ling.key == nil ? L("粘贴") : L("更换")).font(.body.weight(.semibold)).foregroundStyle(Ink.ink)+ .padding(.horizontal, 14).frame(minHeight: 46)+ .background(Ink.ground, in: RoundedRectangle(cornerRadius: 14, style: .continuous))+ }+ .buttonStyle(.plain)+ }+ if ling.key != nil { KeyStatus(state: ling.keyState).font(.subheadline.weight(.semibold)) }+ }+ .padding(16)+ }+ Card {+ Link(destination: URL(string: "https://chat.ant-ling.com/platform/api")!) {+ HStack {+ Text("没有 key?去 Ling 拿一个").foregroundStyle(Ink.ink)+ Spacer()+ Image(systemName: "arrow.up.right").font(.footnote.weight(.semibold)).foregroundStyle(Ink.tertiary)+ }+ .padding(.horizontal, 16).frame(minHeight: 50)+ }+ }+ Text("key 只存在这台手机上,不进备份").font(.footnote).foregroundStyle(Ink.tertiary).padding(.horizontal, 16)+ Spacer(minLength: 0)+ VStack(spacing: 6) {+ PrimaryButton(title: L("开始用知了")) { model.finishWelcome() }+ if ling.key == nil {+ Button { model.finishWelcome() } label: {+ Text("以后再填").font(.subheadline).foregroundStyle(Ink.secondary).frame(maxWidth: .infinity, minHeight: 44)+ }+ .buttonStyle(.plain)+ }+ }+ }+ }++ private func save(_ raw: String) {+ let k = raw.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !k.isEmpty else { return }+ draft = ""+ Task { await ling.setKey(k) }+ }+}++extension AppModel {+ /// The sample on step 2: listening starts (in English, the sample's language), and the sample+ /// plays once the microphone is on; the meeting ends shortly after it does, so its last line lands.+ func playSample() {+ let sample = SampleRun.shared+ guard !sample.playing else { return }+ if !room.isRunning {+ fixes.meetingStarted()+ room.start(source: "en-US", target: Pref.targetCode, voices: UserDefaults.standard.bool(forKey: Pref.voices))+ }+ sample.onFinished = { [weak self] in+ DispatchQueue.main.asyncAfter(deadline: .now() + 2) { self?.stopListening() }+ }+ Task {+ for _ in 0..<600 where room.isRunning && room.sessionID == nil { try? await Task.sleep(nanoseconds: 100_000_000) }+ guard room.isRunning, room.sessionID != nil else { return }+ sample.play()+ }+ }++ func stopSample() {+ SampleRun.shared.onFinished = nil+ SampleRun.shared.stop()+ if room.isRunning { stopListening() }+ }++ func finishWelcome() {+ UserDefaults.standard.set(true, forKey: Pref.welcomed)+ showWelcome = false+ debugLog("welcome: done key=\(ling.hasKey)")+ }+}diff --git a/ios/scripts/build.sh b/ios/scripts/build.shindex f9f7660..fed3976 100755--- a/ios/scripts/build.sh+++ b/ios/scripts/build.sh@@ -62,6 +62,7 @@ if [[ "${RELEASE:-}" != 1 ]]; then/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier com.wquguru.cicada.dev" \-c "Set :CFBundleName Cicada Dev" -c "Set :CFBundleDisplayName Cicada Dev" \-c "Add :LiveSubsDev string $STAMP" \+ -c "Set :BGTaskSchedulerPermittedIdentifiers:0 com.wquguru.cicada.dev.import" \-c "Add :CFBundleURLTypes array" -c "Add :CFBundleURLTypes:0 dict" \-c "Add :CFBundleURLTypes:0:CFBundleURLSchemes array" -c "Add :CFBundleURLTypes:0:CFBundleURLSchemes:0 string cicada-dev" \"$PLIST"diff --git a/ios/shared-sources.txt b/ios/shared-sources.txtindex ac450a7..5542d3f 100644--- a/ios/shared-sources.txt+++ b/ios/shared-sources.txt@@ -23,3 +23,4 @@ Sources/Cicada/Recognition.swiftSources/Cicada/CloudHearing.swiftSources/Cicada/SoundKind.swiftSources/Cicada/SpeakerProfiles.swift+Sources/Cicada/FileImport.swift