Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(ios): face-to-face interpreting, each person holding their own half of the screen to talk

wquguru84e5e33c5c34
diff --git a/Resources/en.lproj/Localizable.strings b/Resources/en.lproj/Localizable.strings
index de7e7a6..c1b04e5 100644
--- a/Resources/en.lproj/Localizable.strings
+++ b/Resources/en.lproj/Localizable.strings
@@ -1586,3 +1586,16 @@
"文字记录和纪要" = "Transcript and notes";
"直接发给同事" = "Ready to send to colleagues";
"配原声或视频" = "For the recording or video";
+
+/* iOS: face to face */
+"面对面" = "Face to Face";
+"面对面同声传译" = "Face-to-Face Interpreting";
+"我说和对方说" = "My language and theirs";
+"正在听你说" = "Listening to you";
+"没听清,按住再说一次" = "Didn't catch that. Hold and say it again";
+"没翻译出来,再说一次" = "Couldn't translate that. Say it again";
+"请说…" = "Speak now…";
+"正在念给对方" = "Reading it out";
+"按住下面的按钮说话" = "Hold the button below and speak";
+"松开就念给对方" = "Let go to read it out";
+"对方在说话" = "They're speaking";
diff --git a/Resources/ja.lproj/Localizable.strings b/Resources/ja.lproj/Localizable.strings
index 912d438..7016e20 100644
--- a/Resources/ja.lproj/Localizable.strings
+++ b/Resources/ja.lproj/Localizable.strings
@@ -1586,3 +1586,16 @@
"文字记录和纪要" = "文字起こしと議事メモ";
"直接发给同事" = "そのまま同僚に送れます";
"配原声或视频" = "録音や動画に合わせて";
+
+/* iOS: face to face */
+"面对面" = "対面";
+"面对面同声传译" = "対面で同時通訳";
+"我说和对方说" = "自分の言語と相手の言語";
+"正在听你说" = "あなたの話を聞いています";
+"没听清,按住再说一次" = "聞き取れませんでした。押したままもう一度";
+"没翻译出来,再说一次" = "翻訳できませんでした。もう一度どうぞ";
+"请说…" = "どうぞ…";
+"正在念给对方" = "読み上げ中";
+"按住下面的按钮说话" = "下のボタンを押したまま話してください";
+"松开就念给对方" = "離すと読み上げます";
+"对方在说话" = "相手が話しています";
diff --git a/Resources/ko.lproj/Localizable.strings b/Resources/ko.lproj/Localizable.strings
index 76132f0..0144e0a 100644
--- a/Resources/ko.lproj/Localizable.strings
+++ b/Resources/ko.lproj/Localizable.strings
@@ -1586,3 +1586,16 @@
"文字记录和纪要" = "기록과 회의록";
"直接发给同事" = "동료에게 바로 보내기";
"配原声或视频" = "녹음이나 동영상용";
+
+/* iOS: face to face */
+"面对面" = "대면";
+"面对面同声传译" = "대면 통역";
+"我说和对方说" = "내 언어와 상대 언어";
+"正在听你说" = "말씀을 듣고 있어요";
+"没听清,按住再说一次" = "잘 못 들었어요. 누른 채 다시 말해 주세요";
+"没翻译出来,再说一次" = "번역하지 못했어요. 다시 말해 주세요";
+"请说…" = "말씀하세요…";
+"正在念给对方" = "읽어 주는 중";
+"按住下面的按钮说话" = "아래 버튼을 누른 채 말하세요";
+"松开就念给对方" = "떼면 읽어 줍니다";
+"对方在说话" = "상대가 말하는 중";
diff --git a/Resources/zh-Hans.lproj/Localizable.strings b/Resources/zh-Hans.lproj/Localizable.strings
index eb018a4..acaa986 100644
--- a/Resources/zh-Hans.lproj/Localizable.strings
+++ b/Resources/zh-Hans.lproj/Localizable.strings
@@ -1491,3 +1491,16 @@
"文字记录和纪要" = "文字记录和纪要";
"直接发给同事" = "直接发给同事";
"配原声或视频" = "配原声或视频";
+
+/* iOS: face to face */
+"面对面" = "面对面";
+"面对面同声传译" = "面对面同声传译";
+"我说和对方说" = "我说和对方说";
+"正在听你说" = "正在听你说";
+"没听清,按住再说一次" = "没听清,按住再说一次";
+"没翻译出来,再说一次" = "没翻译出来,再说一次";
+"请说…" = "请说…";
+"正在念给对方" = "正在念给对方";
+"按住下面的按钮说话" = "按住下面的按钮说话";
+"松开就念给对方" = "松开就念给对方";
+"对方在说话" = "对方在说话";
diff --git a/ios/Sources/Cicada/CicadaApp.swift b/ios/Sources/Cicada/CicadaApp.swift
index 48153c0..d33d5e3 100644
--- a/ios/Sources/Cicada/CicadaApp.swift
+++ b/ios/Sources/Cicada/CicadaApp.swift
@@ -42,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 我说: a `sourceLanguages` locale (对方说 is `source`, as when listening).
+ static let myLang = "iosMyLang"
/// 第一次打开's three steps are done (or skipped).
static let welcomed = "iosWelcomed"
static var speakerMode: Bool { UserDefaults.standard.string(forKey: hear) == "speaker" }
@@ -108,6 +110,9 @@ final class AppModel: ObservableObject {
ImportBackground.importer = i
return i
}()
+ /// 面对面同声传译 (FaceView), over everything while it is open.
+ lazy var face = FaceToFace(store: store, translator: translator, ling: ling)
+ @Published var showFace = false
/// The meeting whose 导出 sheet is open.
@Published var exporting: String?
/// Why a picked file wasn't imported.
diff --git a/ios/Sources/Cicada/Debug.swift b/ios/Sources/Cicada/Debug.swift
index dcab26b..e742163 100644
--- a/ios/Sources/Cicada/Debug.swift
+++ b/ios/Sources/Cicada/Debug.swift
@@ -251,6 +251,29 @@ extension AppModel {
if let f = ExportFormat(rawValue: p.first ?? ""), let s = store.session(p.count > 1 ? p[1] : selection ?? store.sessions.first?.id) {
debugLog("export file: \((try? f.file(s).path) ?? "failed")")
}
+ // 面对面: face opens it, faceClose ends it; faceSay:<me|them>=<text> is a press heard as that
+ // text without the microphone; facePress / faceRelease:<me|them> hold and let go for real.
+ case "face": openFace()
+ case "faceClose": closeFace()
+ case "faceSay":
+ let p = arg.split(separator: "=", maxSplits: 1).map(String.init)
+ guard p.count == 2, let side = FaceToFace.Side(rawValue: p[0]) else { break }
+ face.debugText = p[1]
+ face.press(side)
+ face.release(side)
+ case "faceTurn":
+ // faceTurn:<me|them>=<said>|<translation>
+ let p = arg.split(separator: "=", maxSplits: 1).map(String.init)
+ let q = p.count == 2 ? p[1].split(separator: "|", maxSplits: 1).map(String.init) : []
+ if q.count == 2, let side = FaceToFace.Side(rawValue: p[0]) { face.debugTurn(side, said: q[0], translation: q[1]) }
+ case "facePress":if let side = FaceToFace.Side(rawValue: arg) { face.press(side) }
+ case "faceRelease": if let side = FaceToFace.Side(rawValue: arg) { face.release(side) }
+ case "faceLangs":
+ // faceLangs:<my locale>,<their locale>
+ let p = arg.split(separator: ",").map(String.init)
+ if p.count == 2, let m = FaceToFace.lang(p[0]), let t = FaceToFace.lang(p[1]) { face.setLanguages(mine: m, theirs: t) }
+ case "faceState":
+ debugLog("face active=\(face.active) phase=\(face.phase) heard=\(face.heard.count) last=\(face.last.map { "\($0.side.rawValue) \($0.said.count)/\($0.translation.count)" } ?? "-") problem=\(face.problem)")
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":
diff --git a/ios/Sources/Cicada/FaceToFace.swift b/ios/Sources/Cicada/FaceToFace.swift
new file mode 100644
index 0000000..fb5b742
--- /dev/null
+++ b/ios/Sources/Cicada/FaceToFace.swift
@@ -0,0 +1,409 @@
+import AVFoundation
+import Foundation
+
+/// 面对面同声传译: two people at one phone, each holding their own button. A press is heard in the
+/// speaker's language on the device; on release it is translated and read out in the other's
+/// language (Ming with a Ling key, else the phone's own voice), while nothing listens. The Mac's
+/// SpeakEngine is bound to the virtual mic; this is the same idea for one speaker and two people.
+/// Each turn is a line of a meeting record: "me" for the phone's owner, "them" for the other.
+@MainActor
+final class FaceToFace: ObservableObject {
+ enum Side: String { case me, them }
+
+ enum Phase: Equatable {
+ case idle
+ /// The side's button is held: what has been heard so far, and its draft translation.
+ case hearing(Side)
+ /// Released: the last words come back and are translated.
+ case translating(Side)
+ /// The translation is read out to the other side.
+ case speaking(Side)
+ }
+
+ /// One turn, as both halves show it.
+ struct Turn: Equatable {
+ var side: Side
+ var said: String
+ var translation: String
+ }
+
+ @Published private(set) var active = false
+ @Published private(set) var phase: Phase = .idle
+ @Published private(set) var heard = ""
+ @Published private(set) var draftTranslation = ""
+ @Published private(set) var last: Turn?
+ /// Why the last turn wasn't read out, in the UI's language; cleared by the next press.
+ @Published private(set) var problem = ""
+ @Published var mine: Lang
+ @Published var theirs: Lang
+
+ private let store: SessionStore
+ private let translator: TranslationService
+ private let ling: LingClient
+ private let mic = FaceMic()
+ private let voice = FaceVoice()
+ private var stream: RecognitionStream?
+ private var reader: Task<Void, Never>?
+ private var finals: [String] = []
+ private var sessionID: String?
+ private var startedAt = Date()
+ private var counter = 0
+ private var draftAsked = Date.distantPast
+ private var turnTask: Task<Void, Never>?
+ /// Debug (`faceSay:`): a press heard as this text, without the microphone.
+ var debugText: String?
+
+ init(store: SessionStore, translator: TranslationService, ling: LingClient) {
+ self.store = store
+ self.translator = translator
+ self.ling = ling
+ mine = Self.lang(UserDefaults.standard.string(forKey: Pref.myLang)) ?? Self.defaultMine
+ theirs = Pref.sourceLang
+ if theirs == mine { theirs = sourceLanguages.first { $0 != mine } ?? sourceLanguages[0] }
+ }
+
+ static func lang(_ locale: String?) -> Lang? { sourceLanguages.first { $0.locale == locale } }
+
+ /// The phone's own language among those the recognizer hears.
+ static var defaultMine: Lang {
+ let code = myLanguage(systemLanguages: Locale.preferredLanguages)
+ return sourceLanguages.first { $0.code == code }
+ ?? sourceLanguages.first { $0.code.hasPrefix(String(code.prefix(2))) }
+ ?? sourceLanguages[2]
+ }
+
+ func lang(_ side: Side) -> Lang { side == .me ? mine : theirs }
+
+ func setLanguages(mine m: Lang, theirs t: Lang) {
+ mine = m
+ theirs = t
+ UserDefaults.standard.set(m.locale, forKey: Pref.myLang)
+ UserDefaults.standard.set(t.locale, forKey: Pref.source)
+ }
+
+ // MARK: The screen
+
+ func open() {
+ guard !active else { return }
+ active = true
+ phase = .idle
+ last = nil
+ problem = ""
+ debugLog("face: open \(mine.locale) ⇄ \(theirs.locale)")
+ }
+
+ /// 结束: the record is kept when anyone was heard.
+ func close() {
+ guard active else { return }
+ cancelTurn()
+ voice.stop()
+ mic.stop()
+ if sessionID != nil {
+ store.end()
+ debugLog("face: closed, \(counter) turns in \(sessionID ?? "")")
+ }
+ sessionID = nil
+ counter = 0
+ active = false
+ phase = .idle
+ }
+
+ // MARK: A turn
+
+ func press(_ side: Side) {
+ guard active else { return }
+ // A press while the other side is read out cuts it short: they have heard enough.
+ if case .speaking = phase { voice.stop() }
+ if case .hearing = phase { return }
+ cancelTurn()
+ heard = ""
+ draftTranslation = ""
+ problem = ""
+ finals = []
+ phase = .hearing(side)
+ let lang = lang(side)
+ debugLog("face: hearing \(side.rawValue) \(lang.locale)")
+ guard debugText == nil else { return }
+ turnTask = Task {
+ do {
+ guard await AVAudioApplication.requestRecordPermission() else {
+ fail(L("请在设置里允许知了使用麦克风"))
+ return
+ }
+ if await Recognition.status(lang.locale) != .installed {
+ heard = L("正在下载 \(lang.name) 语音模型…")
+ try await Recognition.install(lang.locale)
+ heard = ""
+ }
+ let stream = try await Recognition.start(lang.locale, drafts: true, speaking: true)
+ guard phase == .hearing(side) else { await stream.cancel(); return }
+ self.stream = stream
+ try mic.start(into: stream)
+ reader = Task { [weak self] in
+ do {
+ for try await piece in stream.results { self?.heard(piece, side: side) }
+ } catch {
+ debugLog("face: recognizer ended: \(error)")
+ }
+ }
+ } catch {
+ debugLog("face: can't listen: \(error)")
+ fail(Recognition.needsUser(error) ? error.localizedDescription : L("没能下载 \(lang.name) 语音模型"))
+ }
+ }
+ }
+
+ func release(_ side: Side) {
+ guard phase == .hearing(side) else { return }
+ phase = .translating(side)
+ turnTask = Task {
+ var text: String
+ if let t = debugText {
+ text = t
+ debugText = nil
+ } else {
+ mic.stop()
+ await stream?.finish()
+ await reader?.value
+ stream = nil
+ reader = nil
+ text = HeardText.fuller(final: finals.joined(separator: " "), draft: heard)
+ }
+ text = HeardText.clean(text).trimmingCharacters(in: .whitespacesAndNewlines)
+ guard phase == .translating(side) else { return }
+ guard text.contains(where: \.isLetter) else {
+ phase = .idle
+ heard = ""
+ problem = L("没听清,按住再说一次")
+ return
+ }
+ heard = text
+ await turn(side, text)
+ }
+ }
+
+ private func heard(_ piece: Recognition.Piece, side: Side) {
+ guard phase == .hearing(side) || phase == .translating(side) else { return }
+ let text = piece.text.trimmingCharacters(in: .whitespacesAndNewlines)
+ if piece.isFinal {
+ if !text.isEmpty { finals.append(text) }
+ heard = finals.joined(separator: " ")
+ } else {
+ heard = (finals + [text]).joined(separator: " ")
+ }
+ translateDraft(side)
+ }
+
+ /// What has been said so far, in the other language, at most every second (Google, never Ling: AGENTS.md).
+ private func translateDraft(_ side: Side) {
+ guard Date().timeIntervalSince(draftAsked) > 1, heard.count >= 4 else { return }
+ draftAsked = Date()
+ let text = heard, from = lang(side).code, to = lang(side == .me ? .them : .me).code
+ Task {
+ guard let out = await translator.translate(text, source: from, target: to, kind: .draft),
+ phase == .hearing(side) else { return }
+ draftTranslation = out
+ }
+ }
+
+ private func turn(_ side: Side, _ text: String) async {
+ let from = lang(side), to = lang(side == .me ? .them : .me)
+ guard let out = await translator.translate(text, source: from.code, target: to.code, kind: .speak),
+ !out.isEmpty else {
+ // Never read out untranslated text (AGENTS.md).
+ guard phase == .translating(side) else { return }
+ phase = .idle
+ problem = L("没翻译出来,再说一次")
+ debugLog("face: translation failed")
+ return
+ }
+ guard phase == .translating(side) else { return }
+ let t = Turn(side: side, said: text, translation: out)
+ last = t
+ heard = ""
+ draftTranslation = ""
+ record(t, from: from, to: to)
+ phase = .speaking(side)
+ contentLog("FACE [\(from.code)→\(to.code)] \(text) => \(out)")
+ await voice.speak(out, language: to.code, ling: ling.hasKey ? ling : nil)
+ if phase == .speaking(side) { phase = .idle }
+ }
+
+ /// Debug (`faceTurn:`): a turn with its translation given, to check the record and the voice
+ /// when no translation service answers (the simulator without a key).
+ func debugTurn(_ side: Side, said: String, translation: String) {
+ guard active else { return }
+ let from = lang(side), to = lang(side == .me ? .them : .me)
+ let t = Turn(side: side, said: said, translation: translation)
+ last = t
+ record(t, from: from, to: to)
+ phase = .speaking(side)
+ turnTask = Task {
+ await voice.speak(translation, language: to.code, ling: ling.hasKey ? ling : nil)
+ if phase == .speaking(side) { phase = .idle }
+ }
+ }
+
+ private func record(_ t: Turn, from: Lang, to: Lang) {
+ if sessionID == nil {
+ let s = store.begin()
+ sessionID = s.id
+ startedAt = s.startedAt
+ }
+ counter += 1
+ store.append(TranscriptLine(id: "t\(counter)", t: Date().timeIntervalSince(startedAt), speaker: t.side.rawValue,
+ src: t.said, dst: t.translation, srcLang: from.code, dstLang: to.code))
+ }
+
+ private func cancelTurn() {
+ turnTask?.cancel()
+ turnTask = nil
+ mic.stop()
+ if let s = stream { Task { await s.cancel() } }
+ stream = nil
+ reader?.cancel()
+ reader = nil
+ }
+
+ private func fail(_ message: String) {
+ cancelTurn()
+ phase = .idle
+ heard = ""
+ problem = message
+ }
+}
+
+/// The microphone for one press: `AVAudioEngine`'s input → the recognizer's format.
+final class FaceMic: @unchecked Sendable {
+ private var engine = AVAudioEngine()
+ private let queue = DispatchQueue(label: "com.wquguru.cicada.face")
+ private let convert = PCMConverter()
+ private var stream: RecognitionStream?
+
+ func start(into stream: RecognitionStream) throws {
+ try FaceAudio.activate()
+ engine = AVAudioEngine()
+ queue.sync { self.stream = stream }
+ let input = engine.inputNode
+ input.installTap(onBus: 0, bufferSize: 4096, format: input.outputFormat(forBus: 0)) { [weak self] buffer, _ in
+ guard let self, let copy = buffer.copy() as? AVAudioPCMBuffer else { return }
+ self.queue.async {
+ guard let s = self.stream, let c = self.convert.convert(copy, to: s.format) else { return }
+ s.append(c)
+ }
+ }
+ engine.prepare()
+ try engine.start()
+ }
+
+ func stop() {
+ guard engine.isRunning else { return }
+ engine.inputNode.removeTap(onBus: 0)
+ engine.stop()
+ queue.sync { stream = nil }
+ }
+}
+
+enum FaceAudio {
+ /// Listening and speaking take turns; the speaker, not the earpiece, so the table hears it.
+ static func activate() throws {
+ let s = AVAudioSession.sharedInstance()
+ if s.category != .playAndRecord || s.mode != .default {
+ try s.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetoothHFP])
+ }
+ try s.setActive(true)
+ }
+}
+
+/// Reads a translation out: Ming's stream (24 kHz 16-bit mono PCM) with a key, the phone's own
+/// voice without one or when Ming sends nothing.
+@MainActor
+final class FaceVoice: NSObject, AVSpeechSynthesizerDelegate {
+ private let engine = AVAudioEngine()
+ private let player = AVAudioPlayerNode()
+ private let synth = AVSpeechSynthesizer()
+ private let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 24_000, channels: 1, interleaved: false)!
+ private var spoken: CheckedContinuation<Void, Never>?
+ private var streaming: Task<Bool, Never>?
+
+ override init() {
+ super.init()
+ engine.attach(player)
+ engine.connect(player, to: engine.mainMixerNode, format: format)
+ synth.delegate = self
+ }
+
+ func speak(_ text: String, language: String, ling: LingClient?) async {
+ // One voice at a time: a turn still being read out ends here.
+ stop()
+ try? FaceAudio.activate()
+ if let ling, let voice = VoiceCatalog.ming(for: language).first, case .ming(let id) = voice.kind {
+ let stream = ling.speech(text, voice: id, language: VoiceCatalog.mingLanguage(for: language))
+ let task = Task { await self.play(stream) }
+ streaming = task
+ if await task.value { debugLog("face: spoke with Ming \(id)"); return }
+ if Task.isCancelled || streaming == nil { return }
+ debugLog("face: Ming sent nothing, the phone's voice instead")
+ }
+ let u = AVSpeechUtterance(string: text)
+ u.voice = AVSpeechSynthesisVoice(language: Locale(identifier: language).language.minimalIdentifier)
+ ?? AVSpeechSynthesisVoice(language: language)
+ await withCheckedContinuation { c in
+ spoken = c
+ synth.speak(u)
+ }
+ debugLog("face: spoke with the phone's voice")
+ }
+
+ /// Plays the chunks as they come; false when none came.
+ private func play(_ stream: AsyncThrowingStream<Data, Error>) async -> Bool {
+ var carry = Data(), frames = 0
+ do {
+ for try await chunk in stream {
+ if Task.isCancelled { break }
+ var bytes = carry + chunk
+ if bytes.count % 2 == 1 { carry = bytes.suffix(1); bytes = bytes.dropLast() } else { carry = Data() }
+ let n = bytes.count / 2
+ guard n > 0, let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(n)) else { continue }
+ buf.frameLength = AVAudioFrameCount(n)
+ bytes.withUnsafeBytes { raw in
+ let src = raw.bindMemory(to: Int16.self)
+ let dst = buf.floatChannelData![0]
+ for i in 0..<n { dst[i] = Float(Int16(littleEndian: src[i])) / 32768 }
+ }
+ if !engine.isRunning { try engine.start() }
+ player.scheduleBuffer(buf, completionHandler: nil)
+ if !player.isPlaying { player.play() }
+ frames += n
+ }
+ } catch {
+ debugLog("face: Ming failed: \(error)")
+ }
+ guard frames > 0 else { return false }
+ // Wait out what is queued: the length of the audio from when it started, roughly.
+ let seconds = Double(frames) / 24_000
+ if let t = player.lastRenderTime, let p = player.playerTime(forNodeTime: t) {
+ let left = seconds - Double(p.sampleTime) / p.sampleRate
+ if left > 0 { try? await Task.sleep(nanoseconds: UInt64((left + 0.2) * 1_000_000_000)) }
+ }
+ player.stop()
+ return true
+ }
+
+ func stop() {
+ streaming?.cancel()
+ streaming = nil
+ player.stop()
+ if synth.isSpeaking { synth.stopSpeaking(at: .immediate) }
+ // Its caller returns now rather than waiting on a voice that was cut.
+ if let s = spoken { spoken = nil; s.resume() }
+ }
+
+ nonisolated func speechSynthesizer(_ s: AVSpeechSynthesizer, didFinish u: AVSpeechUtterance) {
+ MainActor.assumeIsolated { spoken?.resume(); spoken = nil }
+ }
+
+ nonisolated func speechSynthesizer(_ s: AVSpeechSynthesizer, didCancel u: AVSpeechUtterance) {
+ MainActor.assumeIsolated { spoken?.resume(); spoken = nil }
+ }
+}
diff --git a/ios/Sources/Cicada/FaceView.swift b/ios/Sources/Cicada/FaceView.swift
new file mode 100644
index 0000000..87fa362
--- /dev/null
+++ b/ios/Sources/Cicada/FaceView.swift
@@ -0,0 +1,248 @@
+import SwiftUI
+
+/// 面对面, as the design: the top half turned around for the person across the table, each half with
+/// its own hold-to-talk button, and between them 结束 and the two languages. Each half speaks its
+/// own language, so the other person's half is in theirs (the app's strings where it has them).
+struct FaceView: View {
+ @EnvironmentObject var model: AppModel
+ @ObservedObject var face: FaceToFace
+
+ var body: some View {
+ VStack(spacing: 10) {
+ FaceHalf(face: face, side: .them).rotationEffect(.degrees(180))
+ middle
+ FaceHalf(face: face, side: .me)
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 6)
+ .frame(maxWidth: 600)
+ .frame(maxWidth: .infinity)
+ .background(Ink.ground.ignoresSafeArea())
+ .preferredColorScheme(.light)
+ .persistentSystemOverlays(.hidden)
+ }
+
+ private var middle: some View {
+ VStack(spacing: 4) {
+ HStack(spacing: 10) {
+ Button { model.closeFace() } label: {
+ Image(systemName: "xmark").font(.system(size: 16, weight: .bold)).foregroundStyle(Ink.ink)
+ .frame(width: 44, height: 44).background(Color.white, in: Circle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel(Text("结束"))
+ Menu {
+ Picker(selection: Binding(get: { face.mine.locale }, set: { pick(mine: $0) })) {
+ ForEach(sourceLanguages, id: \.locale) { Text(verbatim: $0.name).tag($0.locale) }
+ } label: { Text("我说") }
+ Picker(selection: Binding(get: { face.theirs.locale }, set: { pick(theirs: $0) })) {
+ ForEach(sourceLanguages, id: \.locale) { Text(verbatim: $0.name).tag($0.locale) }
+ } label: { Text("对方说") }
+ } label: {
+ HStack(spacing: 8) {
+ Text(verbatim: face.mine.name)
+ Image(systemName: "arrow.left.arrow.right").font(.footnote.weight(.semibold)).foregroundStyle(Ink.secondary)
+ Text(verbatim: face.theirs.name)
+ }
+ .font(.subheadline.weight(.semibold)).foregroundStyle(Ink.ink)
+ .frame(maxWidth: .infinity, minHeight: 44)
+ .background(Color.white, in: Capsule())
+ }
+ .disabled(face.phase != .idle)
+ .accessibilityLabel(Text("我说和对方说"))
+ // Balances the close button, so the languages sit in the middle.
+ Color.clear.frame(width: 44, height: 44)
+ }
+ if !face.problem.isEmpty {
+ Text(verbatim: face.problem).font(.footnote).foregroundStyle(Ink.accentText)
+ } else if case .hearing(.me) = face.phase {
+ HStack(spacing: 6) { LiveDot(); Text("正在听你说") }.font(.footnote.weight(.semibold)).foregroundStyle(Ink.accentText)
+ }
+ }
+ .frame(minHeight: 52)
+ }
+
+ private func pick(mine l: String) {
+ guard let m = FaceToFace.lang(l) else { return }
+ // Picking the other side's language swaps the two.
+ face.setLanguages(mine: m, theirs: m == face.theirs ? face.mine : face.theirs)
+ }
+
+ private func pick(theirs l: String) {
+ guard let t = FaceToFace.lang(l) else { return }
+ face.setLanguages(mine: t == face.mine ? face.theirs : face.mine, theirs: t)
+ }
+}
+
+private struct FaceHalf: View {
+ @ObservedObject var face: FaceToFace
+ let side: FaceToFace.Side
+
+ private var lang: Lang { face.lang(side) }
+ private var other: FaceToFace.Side { side == .me ? .them : .me }
+
+ var body: some View {
+ let (big, small, bigInk) = content
+ VStack(alignment: .leading, spacing: 12) {
+ Text(verbatim: lang.name).font(.footnote).foregroundStyle(Ink.secondary)
+ Text(verbatim: big)
+ .font(.system(size: big.count > 80 ? 20 : 24, weight: .semibold))
+ .foregroundStyle(bigInk ? Ink.ink : Ink.tertiary)
+ .lineSpacing(3)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .animation(nil, value: big)
+ if !small.isEmpty {
+ Text(verbatim: small).font(.subheadline).foregroundStyle(Ink.tertiary).lineLimit(3)
+ }
+ Spacer(minLength: 0)
+ HoldButton(face: face, side: side, label: buttonLabel)
+ .frame(maxWidth: .infinity)
+ }
+ .padding(20)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
+ .background(Color.white, in: RoundedRectangle(cornerRadius: 28, style: .continuous))
+ .overlay {
+ if face.phase == .hearing(side) {
+ RoundedRectangle(cornerRadius: 28, style: .continuous).strokeBorder(Ink.accent, lineWidth: 2)
+ }
+ }
+ .accessibilityElement(children: .contain)
+ }
+
+ /// The big line, the grey one under it, and whether the big one is settled (ink) or not yet.
+ private var content: (String, String, Bool) {
+ switch face.phase {
+ case .hearing(let s) where s == side:
+ return (face.heard.isEmpty ? String(localized: "请说…", bundle: bundle) : face.heard, "", !face.heard.isEmpty)
+ case .hearing:
+ return (face.draftTranslation.isEmpty ? "…" : face.draftTranslation, "", false)
+ case .translating(let s) where s == side:
+ return (face.heard, String(localized: "正在翻译…", bundle: bundle), true)
+ case .translating:
+ return ("…", "", false)
+ case .speaking(let s) where s == side:
+ return (face.last?.said ?? "", String(localized: "正在念给对方", bundle: bundle), true)
+ case .speaking:
+ return (face.last?.translation ?? "", face.last?.said ?? "", true)
+ case .idle:
+ guard let last = face.last else { return (String(localized: "按住下面的按钮说话", bundle: bundle), "", false) }
+ return last.side == side ? (last.said, last.translation, true) : (last.translation, last.said, true)
+ }
+ }
+
+ private var buttonLabel: String {
+ switch face.phase {
+ case .hearing(let s): s == side ? String(localized: "松开就念给对方", bundle: bundle) : String(localized: "对方在说话", bundle: bundle)
+ case .translating, .speaking: String(localized: "按住说话", bundle: bundle)
+ case .idle: String(localized: "按住说话", bundle: bundle)
+ }
+ }
+
+ /// The app's strings in this half's language: languages the app isn't translated into get English.
+ private var bundle: Bundle { Self.bundle(lang.code) }
+
+ static func bundle(_ code: String) -> Bundle {
+ let folder = switch code {
+ case "zh-CN": "zh-Hans"
+ case "zh-TW": "zh-Hant"
+ case "ja", "ko", "en": code
+ default: "en"
+ }
+ return Bundle.main.path(forResource: folder, ofType: "lproj").flatMap(Bundle.init(path:)) ?? .main
+ }
+}
+
+/// The big round button: held, it listens (orange, with rings); let go, it translates and reads out.
+private struct HoldButton: View {
+ @ObservedObject var face: FaceToFace
+ let side: FaceToFace.Side
+ let label: String
+ @State private var held = false
+
+ private var hearing: Bool { face.phase == .hearing(side) }
+ private var otherHearing: Bool { if case .hearing(let s) = face.phase { return s != side } else { return false } }
+
+ var body: some View {
+ VStack(spacing: 12) {
+ ZStack {
+ Circle().fill(hearing ? Ink.accent : Ink.ink).frame(width: 84, height: 84)
+ if hearing {
+ Circle().stroke(Ink.accent.opacity(0.16), lineWidth: 10).frame(width: 104, height: 104)
+ Image(systemName: "waveform").font(.system(size: 30, weight: .semibold)).foregroundStyle(.white)
+ .symbolEffect(.variableColor.iterative, isActive: true)
+ } else {
+ Image(systemName: "mic.fill").font(.system(size: 30, weight: .semibold)).foregroundStyle(.white)
+ }
+ }
+ .frame(width: 110, height: 110)
+ .opacity(otherHearing ? 0.4 : 1)
+ .contentShape(Circle())
+ .gesture(DragGesture(minimumDistance: 0)
+ .onChanged { _ in
+ guard !held, !otherHearing else { return }
+ held = true
+ face.press(side)
+ }
+ .onEnded { _ in
+ guard held else { return }
+ held = false
+ face.release(side)
+ })
+ .accessibilityElement()
+ .accessibilityLabel(Text(verbatim: label))
+ .accessibilityAddTraits(.isButton)
+ // VoiceOver can't hold: a double tap starts, another one stops.
+ .accessibilityAction {
+ if hearing { face.release(side) } else { face.press(side) }
+ }
+ Text(verbatim: label).font(.subheadline.weight(hearing ? .semibold : .regular))
+ .foregroundStyle(hearing ? Ink.ink : Ink.secondary)
+ .accessibilityHidden(true)
+ }
+ .sensoryFeedback(.impact(weight: .medium), trigger: hearing)
+ }
+}
+
+/// 面对面 beside 开始听 on the home screen.
+struct FaceButton: View {
+ @EnvironmentObject var model: AppModel
+ var onGlass = false
+
+ var body: some View {
+ Button { model.openFace() } label: {
+ VStack(spacing: 1) {
+ Image(systemName: "bubble.left.and.text.bubble.right").font(.system(size: 19, weight: .medium))
+ Text("面对面").font(.system(size: 10, weight: .semibold))
+ }
+ .foregroundStyle(Ink.ink)
+ .frame(width: 58, height: 58)
+ .background {
+ if onGlass { Circle().fill(Color.white).shadow(color: Ink.ink.opacity(0.08), radius: 2, y: 1) }
+ }
+ .contentShape(Circle())
+ }
+ .buttonStyle(.plain)
+ .modifier(GlassCircle(on: !onGlass))
+ .accessibilityLabel(Text("面对面同声传译"))
+ }
+}
+
+private struct GlassCircle: ViewModifier {
+ let on: Bool
+ func body(content: Content) -> some View {
+ if on { content.glassEffect(.regular.interactive(), in: Circle()) } else { content }
+ }
+}
+
+extension AppModel {
+ func openFace() {
+ guard !room.isRunning else { return }
+ face.open()
+ showFace = true
+ }
+
+ func closeFace() {
+ face.close()
+ showFace = false
+ }
+}
diff --git a/ios/Sources/Cicada/RecordsView.swift b/ios/Sources/Cicada/RecordsView.swift
index 774c56c..c4a0107 100644
--- a/ios/Sources/Cicada/RecordsView.swift
+++ b/ios/Sources/Cicada/RecordsView.swift
@@ -24,7 +24,11 @@ struct RecordsSplit: View {
HomeTitle(trailing: AnyView(
ImportMenu { GlassIcon(systemName: "arrow.down.to.line") }))
.padding(.top, 6)
- ListenBar().padding(.top, 16)
+ HStack(spacing: 10) {
+ ListenBar()
+ if !room.isRunning { FaceButton() }
+ }
+ .padding(.top, 16)
ImportCard(importer: model.importer)
if store.sessions.isEmpty {
EmptyRecords().frame(maxWidth: .infinity).padding(.top, 40)
@@ -102,7 +106,11 @@ struct PadRoot: View {
.buttonStyle(.plain).accessibilityLabel(Text("设置"))
}))
.padding(.horizontal, 4)
- ListenBar(onGlass: true).padding(.top, 14).padding(.bottom, 12)
+ HStack(spacing: 8) {
+ ListenBar(onGlass: true)
+ if !room.isRunning { FaceButton(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)
diff --git a/ios/Sources/Cicada/RootView.swift b/ios/Sources/Cicada/RootView.swift
index 3009a94..199da4b 100644
--- a/ios/Sources/Cicada/RootView.swift
+++ b/ios/Sources/Cicada/RootView.swift
@@ -19,6 +19,9 @@ 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.showFace, onDismiss: { model.closeFace() }) {
+ FaceView(face: model.face).environmentObject(model)
+ }
.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 } })) {