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.

chore(android): 我说 in 面对面: hold, speak, and the phone reads it out in their language

wqugurua77fcd7cc07a
diff --git a/android/AGENTS.md b/android/AGENTS.md
index da26cab..c7e6917 100644
--- a/android/AGENTS.md
+++ b/android/AGENTS.md
@@ -1,9 +1,10 @@
# AGENTS.md (Android)
-The Android port: listening only. The root `AGENTS.md` applies too (Ling key, `LingClient`, no third-party dependencies, the Mac app as the reference, one `VERSION`). Commands, layout and how to verify are in `README.md`; the plan is `docs/android-plan.md`.
+The Android port: listening, plus 我说 in 面对面 (hold, speak, the phone reads the translation aloud; no virtual mic, so never into another app's call). The root `AGENTS.md` applies too (Ling key, `LingClient`, no third-party dependencies, the Mac app as the reference, one `VERSION`). Commands, layout and how to verify are in `README.md`; the plan is `docs/android-plan.md`.
- Kotlin and the Android framework only: no AndroidX, Compose or other libraries; UI in code, no XML layouts. `core` is plain JVM and must build and test on the Mac.
- The key: `AIKey` in `core/.../Ling.kt`, the `ling-api-key` file in the app's private folder, kept out of backups; every Ling or Ming call goes through `LingClient`.
+- 我说 speaks only `ListenEngine.speakable` text (a translation, never my words) and mutes the segmenter while the phone speaks.
- The overlay is `FLAG_NOT_FOCUSABLE` and `FLAG_SECURE` unless 共享屏幕时让对方看到 is on.
- Shared UI text comes from `Resources/*.lproj/Localizable.strings`; Android-only text is in `app/src/main/strings/`. Run `python3 scripts/strings.py` after changing either.
- Verify with `scripts/test.sh`, then in the emulator with `scripts/cicadactl.sh`. System consent dialogs, vendor background limits and a real microphone need a person.
diff --git a/android/README.md b/android/README.md
index fba1f21..a65b47d 100644
--- a/android/README.md
+++ b/android/README.md
@@ -1,6 +1,6 @@
# 知了 Android 版
-Cicada 的 Android 版,目前只做“听”:把手机里播放的声音(或面对面时麦克风听到的话)变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录。方案和取舍见 [docs/android-plan.md](../docs/android-plan.md)。
+Cicada 的 Android 版:把手机里播放的声音(或面对面时麦克风听到的话)变成双语字幕和实时纪要,存成和 Mac 版同一格式的会议记录。面对面时按住“按住说话”说一句,松开后手机用对方的语言读出来。方案和取舍见 [docs/android-plan.md](../docs/android-plan.md)。
- 声音来源:手机里的声音(`AudioPlaybackCapture`,Android 10 起,排除知了自己;会议和通话 app 系统不让采集)或面对面(麦克风)。
- 识别:Ming(`Ming-3.0-audio-flash`)分段识别,一次请求返回语言、原文和译文;需要 Ling key。和 Windows 版同一套做法。
@@ -50,4 +50,4 @@ scripts/tap.sh "开始听" # 按屏幕上的文字点(系统对话
调试接收器只在开发版的 manifest 里(`app/src/debug/`),没运行或被强行停止时 `cicadactl.sh` 也能叫醒它。
-需要真人和真机:系统授权对话框和厂商系统的后台限制、面对面模式的真实声音(模拟器拿不到 Mac 的麦克风)、蓝牙耳机。
+需要真人和真机:系统授权对话框和厂商系统的后台限制、面对面模式和“我说”的真实声音(模拟器拿不到 Mac 的麦克风),以及手机外放读出来时会不会被自己的麦克风听进去、蓝牙耳机。
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
index 4f19360..70b0b33 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt
@@ -37,6 +37,7 @@ class CicadaApp : Application() {
lateinit var translator: Translator
lateinit var listen: ListenEngine
lateinit var overlay: Overlay
+ lateinit var voice: Voice
val main = Handler(Looper.getMainLooper())
val background = Executors.newCachedThreadPool { r -> Thread(r, "App").apply { isDaemon = true } }
private val observers = LinkedHashSet<() -> Unit>()
@@ -74,6 +75,8 @@ class CicadaApp : Application() {
AacEncoder.encode(pcm)?.also { Log.d("listen: ${pcm.size * 2 / 1024} KB PCM → ${it.bytes.size / 1024} KB ${it.type} in ${System.currentTimeMillis() - t} ms") }
}
overlay = Overlay(this)
+ voice = Voice(this)
+ listen.onSaid = ::speakAloud
listen.onChange(::changed)
notes.onChange(::changed)
store.onChange { changed() }
@@ -164,15 +167,43 @@ class CicadaApp : Application() {
overlayThisMeeting = false
overlay.collapsed = false
listen.start(source, kind)
+ if (kind == "mic") background.execute { voice.warm() }
openLive()
}
+ // MARK: 我说 (面对面)
+
+ fun holdToSay() {
+ // Pressing again while the phone still speaks: stop it, it's my turn.
+ if (voice.speaking) { voice.stop(); listen.muted = false }
+ listen.hold()
+ }
+
+ fun releaseToSay() = listen.release()
+
+ /// My words in their language, out of the phone's speaker. The mic is muted for the segmenter
+ /// meanwhile (and a beat after, for the room's echo) so the phone doesn't hear itself as them.
+ private fun speakAloud(text: String, lang: String) {
+ listen.muted = true
+ changed()
+ val r = voice.speak(text, lang, onStart = { changed() }, onEnd = {
+ main.postDelayed({ if (!voice.speaking) { listen.muted = false; changed() } }, 400)
+ })
+ // A TTS engine that drops the utterance never calls back: don't stay deaf to the other side.
+ if (r == Voice.Result.Spoken) main.postDelayed({ if (listen.muted && !voice.speaking) { listen.muted = false; changed() } }, 3_000L + text.length * 150L)
+ if (r != Voice.Result.Spoken) {
+ listen.muted = false
+ listen.sayFailed(if (r == Voice.Result.NoVoice) Strings.L("手机不会读这个语言") else Strings.L("没能读出来"))
+ }
+ }
+
/// The 正在听 screen, brought to the front.
fun openLive() {
startActivity(Intent(this, ListeningActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT))
}
fun stopListening(then: (() -> Unit)? = null) {
+ voice.stop()
background.execute {
listen.stop()
main.post {
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
index bc0bfd0..78d3b05 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt
@@ -7,6 +7,7 @@ import cicada.Json
import cicada.Strings
import cicada.Log
import cicada.Session
+import cicada.Wav
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@@ -16,6 +17,7 @@ import java.util.concurrent.TimeUnit
/// one JSON line back as the broadcast's result (never meeting text or the key).
/// state | start [playback|mic] | stop | feed <wav in files/> | sample | view notes|subtitles
/// capture on|off | overlay show|hide | show main|live|records|settings|onboarding|record [id] | overlay collapse|expand | key reload
+/// hear|say <wav in files/> (面对面: the other side / me holding 我说) | tts <lang> <text>
/// import <session.json in files/> | onboarded on|off | target <code> | ui <lang> | clip <text>
class DebugReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
@@ -57,6 +59,14 @@ class DebugReceiver : BroadcastReceiver() {
"view" -> app.setView(if (arg == "subtitles") "subtitles" else "notes")
"capture" -> { app.settings.showInCapture = arg == "on"; app.saveSettings(); app.overlay.rebuild() }
"overlay" -> if (arg == "collapse") { app.overlay.collapsed = true; app.overlay.rebuild() } else if (arg == "expand") { app.overlay.collapsed = false; app.overlay.rebuild() } else if (arg == "hide") { app.overlay.forced = false; app.overlay.hide() } else { app.overlay.forced = true; app.overlay.show() }
+ // 面对面 without a voice: `hear` plays a WAV as the other side, `say` as me holding 我说.
+ "hear" -> app.listen.inject(Wav.read(File(app.filesDir, arg).inputStream()))
+ "say" -> { app.holdToSay(); app.listen.inject(Wav.read(File(app.filesDir, arg).inputStream())); app.releaseToSay() }
+ "tts" -> {
+ val (lang, text) = arg.split(Regex("\\s+"), 2).let { it[0] to it.getOrElse(1) { "Hello." } }
+ app.background.execute { Log.d("debug: tts $lang -> ${app.voice.speak(text, lang, {}, {})}") }
+ return mapOf("tts" to lang)
+ }
"target" -> { app.settings.target = arg.ifEmpty { "system" }; app.saveSettings() }
"ui" -> { app.settings.uiLanguage = arg.ifEmpty { "system" }; app.saveSettings(); app.loadStrings(); app.overlay.rebuild() }
// Puts text on the clipboard (the shell can't), so 粘贴 can be tested.
@@ -91,6 +101,7 @@ class DebugReceiver : BroadcastReceiver() {
"lines" to (id?.let { app.store.lines(it).size } ?: 0),
"translated" to (id?.let { app.store.lines(it).count { l -> l.dst != null } } ?: 0),
"pending" to listen.pending,
+ "say" to mapOf("can" to listen.canSay, "holding" to listen.holding, "saying" to listen.saying, "muted" to listen.muted, "speaking" to app.voice.speaking, "their" to listen.theirLanguage, "problem" to listen.sayProblem),
"spoken" to listen.spoken,
"target" to listen.target,
"heardSeconds" to Math.round(listen.heardSeconds * 10) / 10.0,
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/ListeningActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/ListeningActivity.kt
index 03bac63..6fddac6 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/ListeningActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/ListeningActivity.kt
@@ -23,6 +23,11 @@ class ListeningActivity : Activity() {
private lateinit var scroll: ScrollView
private lateinit var badgeText: TextView
private lateinit var sourceText: TextView
+ private lateinit var bottomHost: FrameLayout
+ private var bottomKind: String? = "-"
+ private var sayButton: LinearLayout? = null
+ private var sayLabel: TextView? = null
+ private var sayHelper: TextView? = null
private var tab = 0
private var shown: String? = null
private var unobserve: (() -> Unit)? = null
@@ -56,10 +61,72 @@ class ListeningActivity : Activity() {
addView(ui.divider(), LinearLayout.LayoutParams(-1, 1).apply { leftMargin = ui.dp(16); rightMargin = ui.dp(16) })
addView(scroll, LinearLayout.LayoutParams(-1, 0, 1f))
}
- val bottom = ui.bottomBar(
- ui.button(L("在视频上看"), "quiet", R.drawable.i_pip) { watchOver() },
- ui.button(L("结束"), "primary", R.drawable.i_stop) { end() })
- setContentView(ui.screen(this, null, back = true, ground = Palette.ground, center = badge, bottom = bottom, scroll = false, body = body))
+ bottomHost = FrameLayout(this)
+ buildBottom()
+ setContentView(ui.screen(this, null, back = true, ground = Palette.ground, center = badge, bottom = bottomHost, scroll = false, body = body))
+ }
+
+ /// 面对面 gets 我说 (hold, speak, release: the phone says it in their language) in place of
+ /// 在视频上看, which has no video to go back to.
+ private fun buildBottom() {
+ val kind = cicada.listen.sourceKind
+ if (kind == bottomKind) return
+ bottomKind = kind
+ bottomHost.removeAllViews()
+ sayButton = null; sayLabel = null; sayHelper = null
+ if (kind != "mic") {
+ bottomHost.addView(ui.bottomBar(
+ ui.button(L("在视频上看"), "quiet", R.drawable.i_pip) { watchOver() },
+ ui.button(L("结束"), "primary", R.drawable.i_stop) { end() }))
+ return
+ }
+ val helper = ui.helper("").apply { gravity = android.view.Gravity.CENTER }
+ val say = ui.button(L("按住说话"), "primary", R.drawable.i_mic) {}
+ val label = (0 until say.childCount).map { say.getChildAt(it) }.filterIsInstance<TextView>().first()
+ say.setOnTouchListener { v, e ->
+ when (e.actionMasked) {
+ android.view.MotionEvent.ACTION_DOWN -> {
+ v.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
+ cicada.holdToSay(); updateSay(); true
+ }
+ android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
+ v.performHapticFeedback(android.view.HapticFeedbackConstants.VIRTUAL_KEY)
+ cicada.releaseToSay(); updateSay(); true
+ }
+ else -> true
+ }
+ }
+ // TalkBack's double tap is a click: press once to start, again to finish.
+ say.setOnClickListener { if (cicada.listen.holding) cicada.releaseToSay() else cicada.holdToSay(); updateSay() }
+ val bar = ui.bottomBar(ui.button(L("结束"), "quiet", R.drawable.i_stop) { end() }, say)
+ (say.layoutParams as LinearLayout.LayoutParams).weight = 1.6f
+ val box = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL
+ addView(helper, LinearLayout.LayoutParams(-1, -2).apply { bottomMargin = ui.dp(8); leftMargin = ui.dp(16); rightMargin = ui.dp(16) })
+ addView(bar)
+ }
+ bottomHost.addView(box)
+ sayButton = say; sayLabel = label; sayHelper = helper
+ updateSay()
+ }
+
+ /// The button changes in place: rebuilding it under a finger would lose the hold.
+ private fun updateSay() {
+ val say = sayButton ?: return
+ val app = cicada
+ val l = app.listen
+ val their = NotesViews.languageName(l.theirLanguage)
+ val (text, live) = when {
+ l.holding -> L("松开,说给对方") to true
+ l.saying -> L("正在翻译…") to false
+ app.voice.speaking -> L("正在读…") to true
+ else -> L("按住说话") to false
+ }
+ sayLabel?.text = text
+ say.contentDescription = text
+ say.background = ui.rounded(if (live) Palette.accent else Palette.ink, 16)
+ sayHelper?.text = l.sayProblem ?: L("松开后用 {lang} 读出来").replace("{lang}", their)
+ sayHelper?.setTextColor(if (l.sayProblem != null) Palette.link else Palette.secondary)
}
override fun onSaveInstanceState(out: Bundle) { super.onSaveInstanceState(out); out.putInt("tab", tab) }
@@ -84,6 +151,8 @@ class ListeningActivity : Activity() {
// Ended elsewhere (the notification, the floating window, Android's "stop sharing").
if (!app.listen.listening && app.listen.pending == 0) { openRecord(); return }
badgeText.text = NotesViews.status(app)
+ buildBottom()
+ updateSay()
sourceText.text = NotesViews.sourceLine(app)
val key = NotesViews.liveKey(app) + tab + app.listen.spoken
if (key == shown) return
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt b/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
index 401f8ca..2a58faa 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/NotesViews.kt
@@ -95,7 +95,7 @@ object NotesViews {
return box
}
for (l in lines.dropLast(1).takeLast(earlier)) {
- val texts = ui.stack(2, ui.text(l.src, 13f, Palette.secondary))
+ val texts = ui.stack(2, ui.text(said(l), 13f, Palette.secondary))
if (!l.dst.isNullOrEmpty() && l.dst != l.src) texts.addView(ui.text(l.dst!!, 16f, Palette.ink), ui.lp(top = 2))
box.addView(LinearLayout(ui.context).apply {
orientation = LinearLayout.HORIZONTAL
@@ -108,14 +108,18 @@ object NotesViews {
}
/// The newest line as a card, with the "still listening" dots under it.
+ /// The original as shown above its translation: mine is marked, so it's clear who said it.
+ fun said(l: TranscriptLine) = if (l.speaker == "me") L("你") + " · " + l.src else l.src
+
fun liveCard(ui: Ui, app: CicadaApp, line: TranscriptLine, big: Float, bg: Int = Palette.card, lines: Int = 0, dots: Boolean = true): LinearLayout {
val card = ui.stack(0)
card.background = ui.rounded(bg, 20)
card.setPadding(ui.dp(18), ui.dp(16), ui.dp(18), ui.dp(16))
card.accessibilityLiveRegion = View.ACCESSIBILITY_LIVE_REGION_POLITE
val translated = !line.dst.isNullOrEmpty() && line.dst != line.src
- if (translated) card.addView(ui.text(line.src, 14f, Palette.secondary, lines = if (lines > 0) lines - 1 else 0))
- card.addView(ui.text(line.dst ?: line.src, big, Palette.ink, bold = true, lines = lines).apply { setLineSpacing(0f, 1.25f) }, ui.lp(top = if (translated) 8 else 0))
+ if (!translated && line.speaker == "me") card.addView(ui.text(L("你"), 14f, Palette.secondary))
+ if (translated) card.addView(ui.text(said(line), 14f, Palette.secondary, lines = if (lines > 0) lines - 1 else 0))
+ card.addView(ui.text(line.dst ?: line.src, big, Palette.ink, bold = true, lines = lines).apply { setLineSpacing(0f, 1.25f) }, ui.lp(top = if (translated || line.speaker == "me") 8 else 0))
if (dots && app.listen.listening) card.addView(LinearLayout(ui.context).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
index 3f55d0b..9a76228 100644
--- a/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/RecordsActivity.kt
@@ -204,7 +204,7 @@ class RecordActivity : Activity() {
val l = lines[i]
(row.getChildAt(0) as TextView).text = Languages.clock(l.t)
val texts = row.getChildAt(1) as LinearLayout
- (texts.getChildAt(0) as TextView).text = l.src
+ (texts.getChildAt(0) as TextView).text = NotesViews.said(l)
val dst = texts.getChildAt(1) as TextView
val translated = !l.dst.isNullOrEmpty() && l.dst != l.src
dst.visibility = if (translated) View.VISIBLE else View.GONE
diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt
new file mode 100644
index 0000000..877eb32
--- /dev/null
+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt
@@ -0,0 +1,67 @@
+package com.wquguru.cicada
+
+import android.content.Context
+import android.media.AudioAttributes
+import android.os.Bundle
+import android.speech.tts.TextToSpeech
+import android.speech.tts.UtteranceProgressListener
+import cicada.Log
+import java.util.Locale
+import java.util.concurrent.CountDownLatch
+import java.util.concurrent.TimeUnit
+
+/// The system's text-to-speech, for saying my translated words to the person in front of me.
+/// Only ever given a translation (ListenEngine.said checks that): never what I said myself.
+class Voice(private val context: Context) {
+ enum class Result { Spoken, NoVoice, Failed }
+
+ private var tts: TextToSpeech? = null
+ private var ready = CountDownLatch(1)
+ private var ok = false
+ @Volatile var speaking = false; private set
+
+ /// Starts the engine early (it takes ~1 s), so the first sentence isn't late.
+ fun warm() { engine() }
+
+ @Synchronized private fun engine(): TextToSpeech? {
+ tts?.let { return if (ready.await(3, TimeUnit.SECONDS) && ok) it else null }
+ ready = CountDownLatch(1)
+ val t = TextToSpeech(context.applicationContext) { status ->
+ ok = status == TextToSpeech.SUCCESS
+ Log.d("voice: engine ${if (ok) "ready" else "failed $status"}")
+ ready.countDown()
+ }
+ t.setAudioAttributes(AudioAttributes.Builder()
+ .setUsage(AudioAttributes.USAGE_ASSISTANT)
+ .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build())
+ tts = t
+ return if (ready.await(3, TimeUnit.SECONDS) && ok) t else null
+ }
+
+ fun has(lang: String): Boolean {
+ val t = engine() ?: return false
+ val r = t.isLanguageAvailable(Locale.forLanguageTag(lang))
+ return r >= TextToSpeech.LANG_AVAILABLE
+ }
+
+ /// Speaks `text` in `lang`; `onStart` / `onEnd` come on a TTS thread. Call off the main thread
+ /// (waits for the engine the first time).
+ fun speak(text: String, lang: String, onStart: () -> Unit, onEnd: () -> Unit): Result {
+ val t = engine() ?: return Result.Failed
+ val locale = Locale.forLanguageTag(lang)
+ val avail = t.isLanguageAvailable(locale)
+ if (avail < TextToSpeech.LANG_AVAILABLE) { Log.d("voice: no voice for $lang ($avail)"); return Result.NoVoice }
+ t.language = locale
+ t.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
+ override fun onStart(id: String) { speaking = true; Log.d("voice: start $lang"); onStart() }
+ override fun onDone(id: String) { speaking = false; Log.d("voice: done"); onEnd() }
+ @Deprecated("Deprecated in Java") override fun onError(id: String) { speaking = false; Log.d("voice: error"); onEnd() }
+ override fun onError(id: String, code: Int) { speaking = false; Log.d("voice: error $code"); onEnd() }
+ override fun onStop(id: String, interrupted: Boolean) { speaking = false; onEnd() }
+ })
+ val r = t.speak(text, TextToSpeech.QUEUE_FLUSH, Bundle(), "said-${System.nanoTime()}")
+ return if (r == TextToSpeech.SUCCESS) Result.Spoken else Result.Failed
+ }
+
+ fun stop() { tts?.stop() }
+}
diff --git a/android/app/src/main/strings/en.lproj/Android.strings b/android/app/src/main/strings/en.lproj/Android.strings
index 4284cfc..68c8a9d 100644
--- a/android/app/src/main/strings/en.lproj/Android.strings
+++ b/android/app/src/main/strings/en.lproj/Android.strings
@@ -100,3 +100,13 @@
"正在加载…" = "Loading…";
"添加到快捷设置" = "Add to Quick Settings";
"下拉通知栏,一键开始或结束听" = "Pull down from the top to start or end listening in one tap";
+"手机不会读这个语言" = "This phone can't speak that language";
+"没能读出来" = "Couldn't read it aloud";
+"松开,说给对方" = "Release to speak";
+"正在读…" = "Speaking…";
+"松开后用 {lang} 读出来" = "Release to say it in {lang}";
+"按住说完再松开" = "Hold until you've finished speaking";
+"没听清,再说一次" = "Didn't catch that. Try again";
+"这句已经是对方的语言" = "That's already in their language";
+"没翻译出来,再说一次" = "Couldn't translate. Try again";
+"没听到声音,靠近手机再说" = "Didn't hear anything. Move closer and try again";
diff --git a/android/app/src/main/strings/ja.lproj/Android.strings b/android/app/src/main/strings/ja.lproj/Android.strings
index ddac37b..2f3a5cd 100644
--- a/android/app/src/main/strings/ja.lproj/Android.strings
+++ b/android/app/src/main/strings/ja.lproj/Android.strings
@@ -100,3 +100,13 @@
"正在加载…" = "読み込み中…";
"添加到快捷设置" = "クイック設定に追加";
"下拉通知栏,一键开始或结束听" = "上から引き下ろして、ワンタップで聞き取りを開始・終了";
+"手机不会读这个语言" = "この言語は端末で読み上げできません";
+"没能读出来" = "読み上げできませんでした";
+"松开,说给对方" = "離すと相手に伝えます";
+"正在读…" = "読み上げ中…";
+"松开后用 {lang} 读出来" = "離すと{lang}で読み上げます";
+"按住说完再松开" = "話し終えるまで押したまま";
+"没听清,再说一次" = "聞き取れませんでした。もう一度";
+"这句已经是对方的语言" = "すでに相手の言語です";
+"没翻译出来,再说一次" = "翻訳できませんでした。もう一度";
+"没听到声音,靠近手机再说" = "声が聞こえません。近づいてもう一度";
diff --git a/android/app/src/main/strings/ko.lproj/Android.strings b/android/app/src/main/strings/ko.lproj/Android.strings
index 3c8d708..e2c9908 100644
--- a/android/app/src/main/strings/ko.lproj/Android.strings
+++ b/android/app/src/main/strings/ko.lproj/Android.strings
@@ -100,3 +100,13 @@
"正在加载…" = "불러오는 중…";
"添加到快捷设置" = "빠른 설정에 추가";
"下拉通知栏,一键开始或结束听" = "위에서 끌어내려 한 번에 듣기 시작·종료";
+"手机不会读这个语言" = "이 언어는 휴대폰이 읽을 수 없어요";
+"没能读出来" = "소리 내어 읽지 못했어요";
+"松开,说给对方" = "떼면 상대에게 전해요";
+"正在读…" = "읽는 중…";
+"松开后用 {lang} 读出来" = "떼면 {lang}(으)로 읽어 줘요";
+"按住说完再松开" = "말을 마칠 때까지 누르고 있어요";
+"没听清,再说一次" = "잘 못 들었어요. 다시 말해 주세요";
+"这句已经是对方的语言" = "이미 상대방 언어예요";
+"没翻译出来,再说一次" = "번역하지 못했어요. 다시 말해 주세요";
+"没听到声音,靠近手机再说" = "소리가 안 들려요. 가까이에서 다시 말해 주세요";
diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
index fcf947f..a556231 100644
--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt
+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt
@@ -27,6 +27,8 @@ object Tests {
"closesInterruptedMeetings" to ::closesInterruptedMeetings,
"displayTitle" to ::displayTitle,
"parsesMingReplies" to ::parsesMingReplies,
+ "speaksOnlyTranslations" to ::speaksOnlyTranslations,
+ "holdToSayAndEchoGate" to ::holdToSayAndEchoGate,
"normalizesLanguages" to ::normalizesLanguages,
"cleansTranslations" to ::cleansTranslations,
"joinsCutSentences" to ::joinsCutSentences,
@@ -476,4 +478,70 @@ object Tests {
} finally { LingClient.spacing = old }
}
+ fun speaksOnlyTranslations() {
+ fun me(src: String, dst: String?, from: String, to: String) =
+ ListenEngine.speakable(TranscriptLine(speaker = "me", src = src, dst = dst, srcLang = from, dstLang = to))
+ equal("Hello.", me("你好。", "Hello.", "zh-CN", "en"), "my translation is spoken")
+ equal(null, me("你好。", null, "zh-CN", "en"), "no translation, nothing spoken")
+ equal(null, me("Hello.", "Hello.", "en", "en"), "already their language: not spoken")
+ equal(null, me("你好。", "你好。", "zh-CN", "en"), "an echo of my words isn't a translation")
+ equal(null, me("你好", " ", "zh", "en"), "blank")
+ equal(null, ListenEngine.speakable(TranscriptLine(speaker = "them", src = "Hi", dst = "嗨", srcLang = "en", dstLang = "zh-CN")), "never the other side")
+ check(Languages.same("zh", "zh-CN") && !Languages.same("zh-CN", "zh-TW") && !Languages.same("en", "ja"), "same language")
+ }
+
+ private class ManualSource : AudioSource {
+ override var onSamples: ((ShortArray) -> Unit)? = null
+ override var onEnded: ((String?) -> Unit)? = null
+ override fun start() {}
+ override fun stop() {}
+ fun push(pcm: ShortArray) { var i = 0; while (i < pcm.size) { onSamples?.invoke(pcm.copyOfRange(i, minOf(pcm.size, i + 1600))); i += 1600 } }
+ }
+
+ fun holdToSayAndEchoGate() {
+ // The other side speaks English; I hold and say something (a different length of tone),
+ // then the phone "speaks" while a tone plays: that must not become the other side's line.
+ val fake = Fake { body ->
+ val system = content(body, 0) as String
+ if (system.contains("into English")) reply("LANG: zh-CN\nORIGINAL: 你好。\nTRANSLATION: Hello.")
+ else if (body.contains("Ming-3.0-audio-flash")) {
+ val url = content(body, 1).arr()[0].obj()!!["audio_url"].obj()!!["url"] as String
+ reply(if (url.length < 60_000) "LANG: en\nORIGINAL: First one.\nTRANSLATION: 第一句。" else "LANG: en\nORIGINAL: Echo.\nTRANSLATION: 回声。")
+ } else reply("{}")
+ }
+ val old = LingClient.spacing
+ LingClient.spacing = 0.05
+ try {
+ val ling = client(fake)
+ val store = SessionStore()
+ val engine = ListenEngine(ling, Translator(ling), store, NotesEngine(ling, store), AppSettings(target = "zh-CN"))
+ val said = CountDownLatch(1)
+ var spoken: Pair<String, String>? = null
+ engine.onSaid = { text, lang -> spoken = text to lang; said.countDown() }
+ val src = ManualSource()
+ engine.start(src, "mic")
+ check(engine.canSay, "面对面 can say")
+ equal("en", engine.theirLanguage, "English before anyone spoke")
+ src.push(concat(tone(1.0), silence(1.2)))
+ val until = System.currentTimeMillis() + 3000
+ while (engine.spoken == null && System.currentTimeMillis() < until) Thread.sleep(20)
+ engine.hold()
+ src.push(tone(1.2))
+ engine.release()
+ src.push(silence(0.3))
+ check(said.await(3, java.util.concurrent.TimeUnit.SECONDS), "said")
+ equal("Hello." to "en", spoken, "spoken in their language")
+ engine.muted = true
+ src.push(concat(tone(2.0), silence(1.2)))
+ Thread.sleep(300) // mute lasts as long as the voice plays: let the worker take what came in meanwhile
+ engine.muted = false
+ src.push(silence(1.0))
+ Thread.sleep(300)
+ engine.stop()
+ val s = store.get(engine.sessionId!!)!!
+ equal("them:First one.|me:你好。", s.lines.joinToString("|") { "${it.speaker}:${it.src}" }, "my line recorded, the echo dropped")
+ equal("m1", s.lines[1].id, "Mac-style id")
+ check(s.lines[1].t >= 2.0, "my line's time is when I pressed")
+ } finally { LingClient.spacing = old }
+ }
}
diff --git a/android/core/src/main/kotlin/cicada/ListenEngine.kt b/android/core/src/main/kotlin/cicada/ListenEngine.kt
index 68d4a94..0bcc552 100644
--- a/android/core/src/main/kotlin/cicada/ListenEngine.kt
+++ b/android/core/src/main/kotlin/cicada/ListenEngine.kt
@@ -63,6 +63,62 @@ class ListenEngine(
val target: String get() = settings.targetCode
private val END = ShortArray(0)
+ // Hold and release go through the audio queue, so buffers recorded before the press stay the
+ // other side's and those recorded before the release are still mine.
+ private val HOLD = ShortArray(0)
+ private val RELEASE = ShortArray(0)
+
+ // MARK: 我说 (面对面 only): hold, say something, release → Ming → spoken in their language.
+
+ /// Speaks my words to the person in front of me: `text` is always a translation (see `speakable`).
+ var onSaid: ((text: String, lang: String) -> Unit)? = null
+ /// The button is down.
+ @Volatile var holding = false; private set
+ /// My words are at Ming.
+ @Volatile var saying = false; private set
+ /// Set while the phone speaks: the mic would hear the translation as the other side, so the
+ /// segmenter gets silence instead.
+ @Volatile var muted = false
+ /// Why the last press said nothing ("没听清,再说一次"); cleared by the next press.
+ @Volatile var sayProblem: String? = null; private set
+ private val mine = ArrayList<ShortArray>()
+ private var holdStart = 0.0
+ private var saidCount = 0
+
+ val canSay: Boolean get() = listening && sourceKind == "mic"
+
+ /// Who I'm talking to speaks the meeting's language; before they have said anything (or when
+ /// it is mine), English, or Chinese for an English speaker (the Mac always falls back to English).
+ val theirLanguage: String get() {
+ val me = target
+ val heard = spoken
+ if (heard != null && !Languages.same(heard, me)) return heard
+ return if (me.startsWith("en")) "zh-CN" else "en"
+ }
+
+ fun hold() {
+ if (!canSay || holding) return
+ holding = true
+ sayProblem = null
+ audio?.offer(HOLD)
+ changed()
+ }
+
+ /// The app couldn't speak a translation ("手机没有这个语言的语音").
+ fun sayFailed(why: String) { sayProblem = why; changed() }
+
+ /// Debug: audio as if the source had just delivered it (the emulator's microphone is silent).
+ fun inject(pcm: ShortArray) {
+ var i = 0
+ while (i < pcm.size) { audio?.offer(pcm.copyOfRange(i, minOf(pcm.size, i + 1600))); i += 1600 }
+ }
+
+ fun release() {
+ if (!holding) return
+ holding = false
+ audio?.offer(RELEASE)
+ changed()
+ }
fun start(from: AudioSource, kind: String) {
if (listening) return
@@ -74,6 +130,7 @@ class ListenEngine(
nextToDeliver = 1; lineCount = 0; last = null; lastEnd = 0.0
hint = null; candidate = null; candidateVotes = 0; problem = null
}
+ holding = false; saying = false; muted = false; sayProblem = null; saidCount = 0
heardSeconds = 0.0; peak = 0.0
notes.language = { Languages.englishName(settings.notesCode) }
notes.begin(session.id)
@@ -83,10 +140,15 @@ class ListenEngine(
audio = queue
// One worker owns the segmenter: audio callbacks only queue buffers.
worker = Thread({
+ var mineOpen = false
while (true) {
val buf = queue.take()
if (buf === END) break
- segmenter.feed(buf)
+ if (buf === HOLD) { mineOpen = true; synchronized(mine) { mine.clear() }; holdStart = heardSeconds; continue }
+ if (buf === RELEASE) { if (mineOpen) { mineOpen = false; finishSaying() }; continue }
+ if (mineOpen) synchronized(mine) { mine.add(buf) }
+ // Silence, not nothing, so the segmenter's clock keeps step with the meeting's.
+ segmenter.feed(if (mineOpen || muted) ShortArray(buf.size) else buf)
level = Wav.rms(buf)
peak = maxOf(peak * 0.995, level)
heardSeconds += buf.size / Segmenter.RATE.toDouble()
@@ -123,6 +185,60 @@ class ListenEngine(
pool.execute { notes.finish() }
}
+ private fun finishSaying() {
+ val pcm = synchronized(mine) {
+ val all = ShortArray(mine.sumOf { it.size }); var at = 0
+ for (b in mine) { b.copyInto(all, at); at += b.size }
+ mine.clear(); all
+ }
+ if (pcm.size < Segmenter.RATE / 2 || Wav.rms(pcm) < 0.003) {
+ sayProblem = if (pcm.size < Segmenter.RATE / 2) Strings.L("按住说完再松开") else Strings.L("没听到声音,靠近手机再说")
+ changed(); return
+ }
+ saying = true
+ changed()
+ val t = Math.round(holdStart * 1000) / 1000.0
+ pool.execute { say(pcm, t) }
+ }
+
+ private fun say(pcm: ShortArray, t: Double) {
+ val id = sessionId ?: run { saying = false; return }
+ val their = theirLanguage
+ val me = target
+ try {
+ val heard = translator.hear(encode(pcm), their, me)
+ if (heard == null) { sayProblem = Strings.L("没听清,再说一次"); return }
+ var dst = heard.translation
+ if (dst == null && !Languages.same(heard.lang, their)) dst = translator.translate(heard.original, heard.lang, their, Translator.Kind.Sentence)
+ val n = synchronized(gate) { ++saidCount }
+ val line = TranscriptLine(id = "m$n", t = t, speaker = "me", src = heard.original, dst = dst,
+ srcLang = heard.lang, dstLang = their)
+ // The other side's next words start their own line, never joined onto mine.
+ synchronized(gate) { last = null }
+ store.append(id, line.copy())
+ val text = speakable(line)
+ Log.d("listen: said ${heard.lang} -> $their, ${if (text != null) "speaking" else "not spoken"}")
+ when {
+ text != null -> onSaid?.invoke(text, their)
+ Languages.same(heard.lang, their) -> sayProblem = Strings.L("这句已经是对方的语言")
+ else -> sayProblem = Strings.L("没翻译出来,再说一次")
+ }
+ } catch (e: LingException) {
+ sayProblem = when (e.kind) {
+ LingException.Kind.NoKey, LingException.Kind.InvalidKey -> Strings.L("Ling key 无效")
+ LingException.Kind.Network, LingException.Kind.Timeout -> Strings.L("连不上 Ling,检查网络")
+ else -> Strings.L("没听清,再说一次")
+ }
+ Log.d("listen: saying failed ${e.message}")
+ } catch (e: Exception) {
+ sayProblem = Strings.L("没听清,再说一次")
+ Log.d("listen: saying failed ${e.javaClass.simpleName}")
+ } finally {
+ saying = false
+ changed()
+ }
+ }
+
private fun encode(pcm: ShortArray): Clip {
val clip = try { encoder(pcm) } catch (e: Exception) { Log.d("listen: encode failed ${e.message}"); null }
if (clip == null || clip.bytes.isEmpty()) return Clip.wav(pcm)
@@ -222,6 +338,13 @@ class ListenEngine(
}
companion object {
+ /// What may be spoken into the room for a line: my words' translation, never my own words.
+ fun speakable(line: TranscriptLine): String? {
+ val dst = line.dst?.trim() ?: return null
+ if (line.speaker != "me" || dst.isEmpty() || Languages.same(line.srcLang, line.dstLang) || dst == line.src.trim()) return null
+ return dst
+ }
+
/// A segment continues the last line when the cut came mid-sentence: no sentence end on the
/// last line, a short gap, the same language, and the joined line not too long to read.
fun continues(last: TranscriptLine, gap: Double, next: Heard): Boolean {
diff --git a/android/core/src/main/kotlin/cicada/SessionStore.kt b/android/core/src/main/kotlin/cicada/SessionStore.kt
index e37fbeb..821eb19 100644
--- a/android/core/src/main/kotlin/cicada/SessionStore.kt
+++ b/android/core/src/main/kotlin/cicada/SessionStore.kt
@@ -182,7 +182,8 @@ class SessionStore(loadNow: Boolean = true) {
}
b.append("## ${Strings.L("文字记录")}\n\n")
for (l in s.lines) {
- b.append("**${Languages.clock(l.t)}** ${l.src} \n")
+ val who = if (l.speaker == "me") Strings.L("你") + " · " else ""
+ b.append("**${Languages.clock(l.t)}** $who${l.src} \n")
if (!l.dst.isNullOrEmpty() && l.dst != l.src) b.append(l.dst).append("\n")
b.append("\n")
}
diff --git a/android/core/src/main/kotlin/cicada/Support.kt b/android/core/src/main/kotlin/cicada/Support.kt
index 0037be3..7b4092c 100644
--- a/android/core/src/main/kotlin/cicada/Support.kt
+++ b/android/core/src/main/kotlin/cicada/Support.kt
@@ -106,5 +106,12 @@ object Languages {
return if (s >= 3600) "%d:%02d:%02d".format(s / 3600, s / 60 % 60, s % 60) else "%02d:%02d".format(s / 60, s % 60)
}
+ /// The same language for speaking purposes: "zh" and "zh-CN" are, "zh-CN" and "zh-TW" aren't.
+ fun same(a: String, b: String): Boolean {
+ if (a.equals(b, ignoreCase = true)) return true
+ val (x, y) = a.substringBefore('-') to b.substringBefore('-')
+ return x.equals(y, ignoreCase = true) && (!a.contains('-') || !b.contains('-'))
+ }
+
fun isCjkLanguage(code: String) = code.startsWith("zh") || code.startsWith("ja") || code.startsWith("ko")
}
diff --git a/docs/android-plan.md b/docs/android-plan.md
index 46749ec..caeb31e 100644
--- a/docs/android-plan.md
+++ b/docs/android-plan.md
@@ -19,7 +19,9 @@ Android 10 起可以采集其他 app 播放的声音(`AudioPlaybackCapture`)
- 会议记录:列表、双语全文、纪要、分享 Markdown、重命名、删除
- 设置和引导:Ling key → 声音来源(试听)→ 示例会议
-第一版不做:说话、说话人识别、离线识别、录音文件。
+面对面里的“我说”:按住说话,松开后 Ming 译成对方的语言,用系统的文字转语音读出来;读的时候不把手机自己的声音当成对方的话。说进别的 app 的通话做不到(Android 没有虚拟麦克风),不做。
+
+第一版不做:说话人识别、离线识别、录音文件。
最低系统 Android 10(API 29),目标 API 36。