知了 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
fix(android): In person reads your words in a voice you choose for each language, including Ming's with a Ling key
wquguru341afdf45965
diff --git a/android/AGENTS.md b/android/AGENTS.mdindex a302880..6fc1dee 100644--- a/android/AGENTS.md+++ b/android/AGENTS.md@@ -5,7 +5,7 @@ The Android port: listening, plus 我说 in 面对面 (hold, speak, the phone re- 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.- 说话人识别 runs Linux's `native/voiceprint.c` (the Mac's model) through the NDK (`app/src/main/jni`): never copy or fork that C, and keep thresholds, labels and Ling's name prompt the Mac's.- Keys: `AIKey` in `core/.../Ling.kt`, one Keystore-sealed file per AI service in the app's private folder (`ling-api-key`, `ai-key-<service>`, as on the Mac), kept out of backups. The services and their recommended models are `core/.../Providers.kt`; every AI call goes through `LingClient`, which reads the service from settings on each call.-- 我说 speaks only `ListenEngine.speakable` text (a translation, never my words), in the service's voice when it has one (not Ling's), else the phone's, and mutes the segmenter while the phone speaks.+- 我说 speaks only `ListenEngine.speakable` text (a translation, never my words), in the voice chosen for that language (`VoiceCatalog.chosen`: the Mac's catalog, Ming's on Ling; the phone's when that is the choice or the service's voice fails), 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/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex b1e0317..ab12b3e 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -48,6 +48,7 @@<activity android:name=".RecordActivity" android:exported="false" android:parentActivityName=".MainActivity" /><activity android:name=".SettingsActivity" android:exported="false" android:parentActivityName=".MainActivity" /><activity android:name=".AiServiceActivity" android:exported="false" android:parentActivityName=".SettingsActivity" />+ <activity android:name=".VoicesActivity" android:exported="false" android:parentActivityName=".SettingsActivity" /><activity android:name=".WordListActivity" android:exported="false" android:parentActivityName=".SettingsActivity" android:windowSoftInputMode="adjustResize" /><activity android:name=".OnboardingActivity" android:exported="false" /><!-- 导入录音或视频: from 首页, or another app's share sheet (分享到知了). -->diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.ktindex 9848947..271bff8 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/AiServiceActivity.kt@@ -601,10 +601,12 @@ class AiServiceActivity : Activity() {/// A model id without its vendor ("qwen3.8-omni-flash"): the rows are narrow.fun short(id: String) = id.substringAfterLast('/')- /// The service's own voice for 我说 (Gemini on OpenRouter and ZenMux), or null: the phone's.+ /// The service's own voice for 我说 (Ming on Ling, Gemini on OpenRouter and ZenMux), or null:+ /// the phone's. Which of its voices is 读出来的声音's choice.fun cloudVoice(app: CicadaApp): String? {val c = app.ling.config()- if (!app.ling.speaks || c.isLing) return null+ if (!app.ling.speaks) return null+ if (c.isLing) return "Ming"val m = c.voiceModel ?: return nullreturn if ("gemini" in m.lowercase()) "Gemini" else short(m)}diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt b/android/app/src/main/kotlin/com/wquguru/cicada/App.ktindex dbe98c2..793d85b 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt@@ -29,6 +29,7 @@ import cicada.SpeakerNamerimport cicada.SpeakerTaggerimport cicada.Stringsimport cicada.Translator+import cicada.VoiceCatalogimport cicada.Wavimport java.io.Fileimport java.util.Locale@@ -253,16 +254,26 @@ class CicadaApp : Application() {fun releaseToSay() = listen.release()+ /// 读出来的声音 for a language: the one chosen in settings, or its default (VoiceCatalog.chosen).+ fun voiceId(lang: String): String = VoiceCatalog.chosen(settings.speakVoices, lang, ling.config(), ling.speaks)++ /// The service's voice name and Ming's language_id for a voice id (not the phone's).+ private fun cloudArgs(id: String, lang: String): Pair<String, String?> =+ if (id.startsWith(VoiceCatalog.MING)) id.removePrefix(VoiceCatalog.MING) to VoiceCatalog.mingLanguage(lang)+ else id.removePrefix(VoiceCatalog.CLOUD) to null+/// 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.- /// Another AI service with a voice model reads them in its voice (Gemini on OpenRouter and- /// ZenMux); Ling and the rest use the phone's, and so does a cloud voice that fails.+ /// The voice chosen for their language reads them (Ming's on Ling, Gemini's on OpenRouter and+ /// ZenMux); the phone's reads them when that is the choice, and when a service's voice fails.private fun speakAloud(text: String, lang: String) {listen.muted = truechanged()- if (ling.speaks && !ling.config().isLing) {+ val id = voiceId(lang)+ if (id != VoiceCatalog.PHONE) {background.execute {- val r = voice.speakCloud(ling, text, onStart = { changed() }, onEnd = {})+ val (name, language) = cloudArgs(id, lang)+ val r = voice.speakCloud(ling, text, name, language, onStart = { changed() }, onEnd = {})if (r == Voice.Result.Spoken) main.postDelayed({ if (!voice.speaking) { listen.muted = false; changed() } }, 400)else speakWithPhone(text, lang)}@@ -271,6 +282,34 @@ class CicadaApp : Application() {speakWithPhone(text, lang)}+ /// The voice being tried (试听 / 试一句), shown as a spinner on its row.+ @Volatile var previewing: String? = null; private set++ /// Plays a voice on the speaker with a line in `lang` (the Mac's previewVoice); not a meeting+ /// line, so nothing is muted. `failed` comes on the main thread with why nothing played.+ fun previewVoice(id: String, lang: String, text: String = VoiceCatalog.sample(lang), failed: (String) -> Unit = {}) {+ voice.stop()+ previewing = id+ changed()+ fun done() = main.post { if (previewing == id) previewing = null; changed() }+ if (id == VoiceCatalog.PHONE) {+ background.execute {+ val r = voice.speak(text, lang, onStart = {}, onEnd = { done() })+ if (r != Voice.Result.Spoken) {+ done()+ main.post { failed(Strings.L(if (r == Voice.Result.NoVoice) "手机不会读这个语言" else "没能读出来")) }+ }+ }+ return+ }+ background.execute {+ val (name, language) = cloudArgs(id, lang)+ val r = voice.speakCloud(ling, text, name, language, onStart = {}, onEnd = { done() })+ Log.d("voice: preview $id $lang ${r.name}")+ if (r != Voice.Result.Spoken) main.post { failed(Strings.L("没能读出来")) }+ }+ }+private fun speakWithPhone(text: String, lang: String) {val r = voice.speak(text, lang, onStart = { changed() }, onEnd = {main.postDelayed({ if (!voice.speaking) { listen.muted = false; changed() } }, 400)diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.ktindex 007a2db..12eff7c 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt@@ -8,6 +8,7 @@ import cicada.SilentAudioSourceimport cicada.Stringsimport cicada.Logimport cicada.Session+import cicada.VoiceCatalogimport cicada.Wavimport java.io.Fileimport java.util.concurrent.CountDownLatch@@ -23,6 +24,7 @@ import java.util.concurrent.TimeUnit/// provider ling|openrouter|zenmux|custom | ai-model hear|text|voice|notes <id> ("" back to the recommended) | show ai/// ai-base <url> (the custom service's address) · ai-notes same|own · ai-notes-base <url> · notes-key import <file in files/>|remove (the custom service's 纪要)/// key import <file in files/> (sealed as the current service's key, the plain file deleted) | voice-try (设置's 试一句)+/// voice <lang>[=<id>] (读出来的声音: choose, or say it and the options) · voice-preview <lang> [<id>] (试听) · show voices [lang]/// ai-check (重新检查) | ai-check-sim <reason|lowBalance|off> (every check ends that way; the state's ai.check has the steps)/// 改正听错的词: fixes on|off · asknames on|off · silent (a meeting with no audio) · heard <text> · vocab add|remove|state/// fixstate · fixanswer yes|no · fixrevert <line> · fixlater · fixundo · fixedit <line>=<text>[|one][|keep0] · pinyin <text>@@ -129,9 +131,24 @@ class DebugReceiver : BroadcastReceiver() {}// 语音和文字只发给你的服务 (the Mac's aiCustomOnly:on|off): `ai-custom-only on|off`."ai-custom-only" -> { app.setCustomOnly(arg == "on"); return mapOf("ok" to true, "ai" to ai(app)) }- "voice-try" -> app.background.execute {- val r = app.voice.speakCloud(app.ling, "Could you send the revised quote by Friday? We can sign next week.", {}, {})- Log.d("debug: voice-try -> $r")+ "voice-try" -> { app.previewVoice(app.voiceId("en"), "en", SettingsActivity.SAMPLE) { Log.d("debug: voice-try failed") }; return mapOf("voice" to app.voiceId("en")) }+ // 读出来的声音: `voice <lang>=<id>` chooses (en=ming:UK_George, zh=phone; en= back to the+ // default), `voice <lang>` says what it is and what's offered; `voice-preview <lang> <id>` is 试听.+ "voice" -> {+ val lang = arg.substringBefore('=')+ if ('=' in arg) {+ val id = arg.substringAfter('=')+ if (id.isEmpty()) app.settings.speakVoices.remove(VoiceCatalog.key(lang)) else app.settings.speakVoices[VoiceCatalog.key(lang)] = id+ app.saveSettings()+ }+ return mapOf("lang" to lang, "voice" to app.voiceId(lang), "options" to VoiceCatalog.options(lang, app.ling.config()).map { it.id })+ }+ "voice-preview" -> {+ val words = arg.split(Regex("\\s+"), 2)+ val lang = words[0].ifEmpty { "en" }+ val id = words.getOrNull(1) ?: app.voiceId(lang)+ app.previewVoice(id, lang) { Log.d("debug: preview failed $it") }+ return mapOf("previewing" to id)}// 检查更新 against a test feed: the dev build checks only once one is set."updatefeed" -> { app.updates.setFeed(if (arg.isEmpty() || arg.contains("://")) arg else File(app.filesDir, arg).path); app.updates.checkIfDue(0) }@@ -240,6 +257,7 @@ class DebugReceiver : BroadcastReceiver() {"settings" -> open(SettingsActivity::class.java)"words" -> open(WordListActivity::class.java)"ai" -> open(AiServiceActivity::class.java)+ "voices" -> open(VoicesActivity::class.java, arg.substringAfter(' ', "").ifEmpty { null })"onboarding" -> open(OnboardingActivity::class.java)"record" -> open(RecordActivity::class.java, arg.substringAfter(' ', "").ifEmpty { app.store.all().firstOrNull { it.id != app.listen.sessionId || !app.listen.listening }?.id })"records" -> open(RecordsActivity::class.java)diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.ktindex 4eea6ac..fbd064f 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt@@ -14,6 +14,7 @@ import cicada.Languagesimport cicada.Logimport cicada.Stringsimport cicada.Strings.L+import cicada.VoiceCatalog/// 设置, a top-level screen beside 会议记录 (the floating navigation): grouped rows as the Mac/// groups them (AI 服务, 语言, 听对方, 我说 · 面对面, …), each a value that opens its choices in a@@ -82,10 +83,21 @@ class SettingsActivity : Activity() {startActivity(Intent(this, WordListActivity::class.java))})))+ // 读出来的声音: the voice for the language they speak now, chosen per language on its own+ // page (VoicesActivity, the Mac's VoiceSection). 试一句 reads English in English's voice.page.addView(ui.sectionLabel(L("我说 · 面对面")))+ val their = app.listen.theirLanguage+ val theirVoice = VoiceCatalog.option(app.voiceId(their), their, app.ling.config())+ val english = VoiceCatalog.option(app.voiceId("en"), "en", app.ling.config())page.addView(ui.group(listOf(ui.switchRow(L("把我说的翻译给对方"), L("按住说话,松开后用对方的语言读出来"), s.speakBack) { s.speakBack = it; app.saveSettings() },- ui.listRow(L("试一句"), AiServiceActivity.cloudVoice(app)?.let { Strings.LF("用 %@ 的声音读一句英语", it) } ?: L("用手机的声音读一句英语"), trailing = ui.icon(R.drawable.i_play, 20, Palette.ink), chevron = false) { tryVoice() })))+ ui.listRow(L("读出来的声音"), if (app.ling.usable) L("每种语言各记一个声音")+ else if (app.ling.provider.id == "ling") L("填入 Ling key:声音更自然,还能用你自己的声音") else L("填好 AI 服务的 key,声音更自然"),+ trailing = value(theirVoice?.let { VoicesActivity.name(it) } ?: L("手机的声音"))) {+ startActivity(Intent(this, VoicesActivity::class.java).putExtra("id", their))+ },+ ui.listRow(L("试一句"), if (english == null || english.id == VoiceCatalog.PHONE) L("用手机的声音读一句英语") else Strings.LF("用 %@ 的声音读一句英语", english.name),+ trailing = ui.icon(R.drawable.i_play, 20, Palette.ink), chevron = false) { tryVoice() })))page.addView(ui.sectionLabel(L("在其他应用上")))val rows = mutableListOf<View>(@@ -152,22 +164,15 @@ class SettingsActivity : Activity() {ui.choose(this, label, options, selected) { changed(it); shown = null; build() }}- /// A sample of how my words will sound to them (the Mac's 试一句), in English.+ /// A sample of how my words will sound to them (the Mac's 试一句), in English's voice.private fun tryVoice() {val app = cicada- val sample = "Could you send the revised quote by Friday? We can sign next week."- if (AiServiceActivity.cloudVoice(app) != null) {- app.background.execute {- if (app.voice.speakCloud(app.ling, sample, onStart = {}, onEnd = {}) != Voice.Result.Spoken)- app.main.post { android.widget.Toast.makeText(this, L("没能读出来"), android.widget.Toast.LENGTH_SHORT).show() }- }- return- }- val r = cicada.voice.speak("Could you send the revised quote by Friday? We can sign next week.", "en", onStart = {}, onEnd = {})- if (r != Voice.Result.Spoken) android.widget.Toast.makeText(this, if (r == Voice.Result.NoVoice) L("手机不会读这个语言") else L("没能读出来"), android.widget.Toast.LENGTH_SHORT).show()+ app.previewVoice(app.voiceId("en"), "en", SAMPLE) { android.widget.Toast.makeText(this, it, android.widget.Toast.LENGTH_SHORT).show() }}companion object {+ const val SAMPLE = "Could you send the revised quote by Friday? We can sign next week."+/// Debug (`export pick`): open the folder picker once settings is in front.var pickFolder = falsediff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Voice.ktindex 77c486f..a5915d4 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt@@ -70,11 +70,12 @@ class Voice(private val context: Context) {private class Stopped : RuntimeException()@Volatile private var track: AudioTrack? = null- /// Reads `text` in the AI service's voice: its 24 kHz PCM goes into an AudioTrack as it arrives,- /// so the first words play before the rest has come. Blocks until it has played (or `stop`).- /// `onStart` comes with the first sound; `onEnd` always comes. Failed lets the caller fall back- /// to the phone's voice.- fun speakCloud(ling: LingClient, text: String, onStart: () -> Unit, onEnd: () -> Unit): Result {+ /// Reads `text` in the AI service's `voiceName` (Ming's with `language`, Ming's language_id): its+ /// 24 kHz PCM goes into an AudioTrack as it arrives, so the first words play before the rest has+ /// come. Blocks until it has played (or `stop`). `onStart` comes with the first sound; `onEnd`+ /// always comes. Failed lets the caller fall back to the phone's voice.+ fun speakCloud(ling: LingClient, text: String, voiceName: String?, language: String?,+ onStart: () -> Unit, onEnd: () -> Unit): Result {val rate = LingClient.TTS_RATEval t = try {AudioTrack.Builder()@@ -90,7 +91,7 @@ class Voice(private val context: Context) {speaking = truevar frames = 0Ltry {- ling.speech(text) { pcm ->+ ling.speech(text, voiceName, language) { pcm ->if (track !== t) throw Stopped()if (frames == 0L) { t.play(); Log.d("voice: cloud start"); onStart() }t.write(pcm, 0, pcm.size)diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.ktnew file mode 100644index 0000000..10fa674--- /dev/null+++ b/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.kt@@ -0,0 +1,141 @@+package com.wquguru.cicada++import android.app.Activity+import android.content.Intent+import android.content.res.ColorStateList+import android.graphics.Color+import android.graphics.drawable.GradientDrawable+import android.os.Bundle+import android.view.Gravity+import android.view.View+import android.widget.FrameLayout+import android.widget.LinearLayout+import android.widget.ProgressBar+import cicada.Strings+import cicada.Strings.L+import cicada.VoiceCatalog+import cicada.VoiceOption++/// 读出来的声音 (Settings › 我说 · 面对面): the Mac's voice picker (VoicePicker.swift) as a page.+/// Each language remembers its own voice (`speakVoices`); the list is the service's voices for the+/// language (Ming's on Ling), then the phone's, each with 试听. Opened on the language they speak+/// now (the `id` extra); the pill switches language.+class VoicesActivity : Activity() {+ private lateinit var ui: Ui+ private lateinit var page: LinearLayout+ private var unobserve: (() -> Unit)? = null+ private var shown: String? = null+ private lateinit var language: String++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ ui = Ui(this)+ language = intent.getStringExtra("id") ?: cicada.listen.theirLanguage+ page = ui.stack(0).apply { setPadding(ui.dp(16), ui.dp(4), ui.dp(16), ui.dp(24)) }+ setContentView(ui.screen(this, L("读出来的声音"), back = true, ground = Palette.ground, body = page))+ }++ override fun onResume() { super.onResume(); unobserve = cicada.observe(::build); shown = null; build() }+ override fun onPause() { super.onPause(); unobserve?.invoke(); unobserve = null }++ private val now get() = cicada.listen.theirLanguage++ private fun build() {+ val app = cicada+ val ling = app.ling+ val chosen = app.voiceId(language)+ val key = listOf(language, chosen, app.previewing, ling.keyState, ling.provider.id, ling.speaks, app.settings.speakVoices, Strings.language).joinToString("|")+ if (key == shown) return+ shown = key+ page.removeAllViews()++ // "每种语言各记一个声音" for the language they speak now, "对方说…时用" for another, and the pill.+ val current = VoiceCatalog.key(language) == VoiceCatalog.key(now)+ val head = ui.row(10,+ ui.helper(if (current) L("每种语言各记一个声音") else Strings.LF("对方说%@时用", VoiceCatalog.title(language))).apply { layoutParams = ui.weight() },+ pill(VoiceCatalog.title(language) + if (current) L("(当前)") else ""))+ head.setPadding(ui.dp(4), ui.dp(4), 0, ui.dp(10))+ page.addView(head)++ val rows = VoiceCatalog.options(language, ling.config()).map { voiceRow(it, chosen) }+ page.addView(ui.group(rows))+ page.addView(ui.helper(footnote(), Palette.tertiary).apply { setPadding(ui.dp(4), ui.dp(10), ui.dp(4), 0) })+ }++ /// The language menu: the Mac's tabs, the one they speak now marked.+ private fun pill(label: String) = ui.row(6,+ ui.text(label, 14f, Palette.ink, medium = true, lines = 1),+ ui.icon(R.drawable.i_chevron_down, 16, Palette.tertiary)).apply {+ setPadding(ui.dp(14), ui.dp(8), ui.dp(12), ui.dp(8))+ minimumHeight = ui.dp(40)+ contentDescription = label+ ui.tappable(this, 20, ui.rounded(Palette.card, 20, stroke = Palette.line)) {+ val nowKey = VoiceCatalog.key(now)+ ui.choose(this@VoicesActivity, L("读出来的声音"),+ VoiceCatalog.languages.map { (k, t) -> k to t + if (k == nowKey) L("(当前)") else "" },+ VoiceCatalog.key(language)) { language = if (it == "zh") "zh-CN" else it; shown = null; build() }+ }+ }++ private fun voiceRow(v: VoiceOption, chosen: String): View {+ val app = cicada+ val selected = v.id == chosen+ val usable = v.id == VoiceCatalog.PHONE || app.ling.speaks+ val row = ui.listRow(name(v), if (usable) VoicesActivity.summary(v) else L("需要 key"),+ leading = playButton(v.id, selected, usable), trailing = radio(selected), chevron = false) {+ if (!usable) return@listRow+ app.settings.speakVoices[VoiceCatalog.key(language)] = v.id+ app.saveSettings()+ shown = null; build()+ }+ if (selected) row.background = ui.ripple(GradientDrawable().apply { setColor(Palette.accentPale) })+ if (!usable) row.alpha = 0.5f+ row.isSelected = selected+ return row+ }++ /// 试听: a round play button (accent when the voice is the chosen one), a spinner while it plays.+ private fun playButton(id: String, highlighted: Boolean, enabled: Boolean): View {+ val app = cicada+ val playing = app.previewing == id+ return FrameLayout(this).apply {+ contentDescription = L("试听")+ background = ui.rounded(if (highlighted) Palette.accent else Palette.ground, 18)+ if (playing) addView(ProgressBar(context, null, android.R.attr.progressBarStyleSmall).apply {+ indeterminateTintList = ColorStateList.valueOf(if (highlighted) Color.WHITE else Palette.accent)+ }, FrameLayout.LayoutParams(ui.dp(18), ui.dp(18), Gravity.CENTER))+ else addView(ui.icon(R.drawable.i_play, 16, if (highlighted) Color.WHITE else Palette.ink), FrameLayout.LayoutParams(ui.dp(16), ui.dp(16), Gravity.CENTER))+ layoutParams = LinearLayout.LayoutParams(ui.dp(36), ui.dp(36))+ if (enabled && !playing) ui.tappable(this, 18, background) {+ app.previewVoice(id, language) { android.widget.Toast.makeText(this@VoicesActivity, it, android.widget.Toast.LENGTH_SHORT).show() }+ }+ }+ }++ private fun radio(on: Boolean) = FrameLayout(this).apply {+ background = GradientDrawable().apply { shape = GradientDrawable.OVAL; setStroke(ui.dp(2), if (on) Palette.accent else Palette.outline) }+ if (on) addView(ui.dot(Palette.accent, 10), FrameLayout.LayoutParams(ui.dp(10), ui.dp(10), Gravity.CENTER))+ // listRow sizes its trailing view by content: an empty ring needs its own size.+ minimumWidth = ui.dp(20); minimumHeight = ui.dp(20)+ layoutParams = LinearLayout.LayoutParams(ui.dp(20), ui.dp(20))+ importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO+ }++ private fun footnote(): String {+ val ling = cicada.ling+ if (ling.provider.id != "ling") return if (ling.speaks) Strings.LF("%@ 用不了时,自动换手机的声音", ling.provider.name) else L("这个服务不出声音,用手机的声音")+ return if (ling.usable) L("Ling 不可用时自动换成手机的声音") else L("填入 Ling key 后可用 Ming 声音和你自己的声音")+ }++ companion object {+ /// The name a voice shows by (the phone's and the user's own are UI text).+ fun name(v: VoiceOption): String = if (v.id == VoiceCatalog.PHONE) L(v.name) else v.name++ /// "女 · 美式 · Ming" / "本机 · 最快": who it is and where it comes from.+ fun summary(v: VoiceOption): String = when {+ v.id == VoiceCatalog.PHONE -> listOf(L("本机"), L("最快")).joinToString(" · ")+ v.id.startsWith(VoiceCatalog.MING) -> (v.tags.take(2).map { L(it) } + "Ming").joinToString(" · ")+ else -> v.tags.map { L(it) }.joinToString(" · ")+ }+ }+}diff --git a/android/app/src/main/strings/en.lproj/Android.strings b/android/app/src/main/strings/en.lproj/Android.stringsindex 9d587fc..d76a7ba 100644--- a/android/app/src/main/strings/en.lproj/Android.strings+++ b/android/app/src/main/strings/en.lproj/Android.strings@@ -226,3 +226,8 @@"最多 %lld 个,满了优先用最近的。只存在这台手机上" = "Up to %lld, recent ones first. Stored only on this phone";"点一下改写法" = "Tap to change the spelling";"重新选" = "Choose again";+"读出来的声音" = "Voice they hear";+"手机的声音" = "Phone voice";+"Ling 不可用时自动换成手机的声音" = "Falls back to the phone's voice when Ling is unavailable";+"%@ 用不了时,自动换手机的声音" = "Falls back to the phone's voice if %@ is unavailable";+"这个服务不出声音,用手机的声音" = "This service has no voice; using the phone's voice";diff --git a/android/app/src/main/strings/ja.lproj/Android.strings b/android/app/src/main/strings/ja.lproj/Android.stringsindex 1a80643..af80ada 100644--- a/android/app/src/main/strings/ja.lproj/Android.strings+++ b/android/app/src/main/strings/ja.lproj/Android.strings@@ -226,3 +226,8 @@"最多 %lld 个,满了优先用最近的。只存在这台手机上" = "最大 %lld 個、最近使ったものを優先。このスマホにだけ保存";"点一下改写法" = "タップして表記を変更";"重新选" = "選び直す";+"读出来的声音" = "読み上げる声";+"手机的声音" = "スマホの声";+"Ling 不可用时自动换成手机的声音" = "Ling が使えないときはスマホの声に切り替え";+"%@ 用不了时,自动换手机的声音" = "%@ が使えないときはスマホの声に切り替え";+"这个服务不出声音,用手机的声音" = "このサービスは声が出ないため、スマホの声を使用";diff --git a/android/app/src/main/strings/ko.lproj/Android.strings b/android/app/src/main/strings/ko.lproj/Android.stringsindex fb6ed2d..b407a02 100644--- a/android/app/src/main/strings/ko.lproj/Android.strings+++ b/android/app/src/main/strings/ko.lproj/Android.strings@@ -226,3 +226,8 @@"最多 %lld 个,满了优先用最近的。只存在这台手机上" = "최대 %lld개, 최근 것을 우선. 이 휴대전화에만 저장";"点一下改写法" = "탭해서 표기 바꾸기";"重新选" = "다시 선택";+"读出来的声音" = "읽어 줄 목소리";+"手机的声音" = "휴대전화 음성";+"Ling 不可用时自动换成手机的声音" = "Ling을 쓸 수 없으면 휴대전화 음성으로 전환";+"%@ 用不了时,自动换手机的声音" = "%@을(를) 쓸 수 없으면 휴대전화 음성으로 전환";+"这个服务不出声音,用手机的声音" = "이 서비스는 음성이 없어 휴대전화 음성 사용";diff --git a/android/cli/src/main/kotlin/cicada/cli/Main.kt b/android/cli/src/main/kotlin/cicada/cli/Main.ktindex f4b4047..6d59428 100644--- a/android/cli/src/main/kotlin/cicada/cli/Main.kt+++ b/android/cli/src/main/kotlin/cicada/cli/Main.kt@@ -7,6 +7,7 @@// cicada-cli hear <file.wav> [--target zh-CN] one file to the hear model (Ming on Ling), raw reply printed// cicada-cli say <file.wav> [--to en] [--out said.wav]// 我说 · 面对面: what I say heard and translated, then read by the service's voice into a WAV+// cicada-cli speak <text> [--voice US_Emma] [--lang ja] [--out speak.wav] one line in the service's voice// cicada-cli segments <file.wav> where the segmenter cuts// cicada-cli roundtrip <session.json>… reads and writes records, says if a byte changed//@@ -110,6 +111,24 @@ fun main(argv: Array<String>) {samples.size / LingClient.TTS_RATE.toDouble(), first, System.currentTimeMillis() - t, file.path))exitProcess(0)}+ "speak" -> {+ // speak <text> [--voice US_Emma] [--lang ja] [--out speak.wav]: one line in a service voice.+ Log.echo = args.contains("--log")+ val ling = client(settings())+ val voice = opt("--voice", "").ifEmpty { null }+ val lang = opt("--lang", "").ifEmpty { null }+ val out = java.io.ByteArrayOutputStream()+ val t = System.currentTimeMillis()+ var first = 0L+ ling.speech(args[1], voice, lang) { if (first == 0L) first = System.currentTimeMillis() - t; out.write(it) }+ val bytes = out.toByteArray()+ val samples = ShortArray(bytes.size / 2) { ((bytes[2 * it].toInt() and 0xff) or (bytes[2 * it + 1].toInt() shl 8)).toShort() }+ val file = File(opt("--out", "speak.wav"))+ file.writeBytes(Wav.bytes(samples, LingClient.TTS_RATE))+ println("voice ${ling.config().voiceModel} ${voice ?: "-"}: %.1f s of audio, first sound after %d ms, all in %d ms -> %s".format(+ samples.size / LingClient.TTS_RATE.toDouble(), first, System.currentTimeMillis() - t, file.path))+ exitProcess(if (samples.isEmpty()) 1 else 0)+ }"listen" -> {Log.echo = args.contains("--log")val settings = settings(opt("--target", "zh-CN"))diff --git a/android/cli/src/main/kotlin/cicada/cli/Tests.kt b/android/cli/src/main/kotlin/cicada/cli/Tests.ktindex e232244..72fb9a6 100644--- a/android/cli/src/main/kotlin/cicada/cli/Tests.kt+++ b/android/cli/src/main/kotlin/cicada/cli/Tests.kt@@ -92,7 +92,7 @@ object Tests {"notesPromptNamesTheVoices" to ::notesPromptNamesTheVoices,"aHalfSentenceJoinsOnlyTheSameVoice" to ::aHalfSentenceJoinsOnlyTheSameVoice,"slowVoiceprintsNeverHoldSubtitlesBack" to ::slowVoiceprintsNeverHoldSubtitlesBack,- ) + ProviderTests.tests + AICheckTests.tests + FixTests.tests + ShareTests.tests + FolderExportTests.tests+ ) + ProviderTests.tests + VoiceTests.tests + AICheckTests.tests + FixTests.tests + ShareTests.tests + FolderExportTests.testsvar passed = 0; var failed = 0for ((name, test) in tests) {try { test(); passed++ } catch (e: Throwable) { failed++; println("FAIL $name: ${e.message ?: e.javaClass.simpleName}") }diff --git a/android/cli/src/main/kotlin/cicada/cli/VoiceTests.kt b/android/cli/src/main/kotlin/cicada/cli/VoiceTests.ktnew file mode 100644index 0000000..f5c498e--- /dev/null+++ b/android/cli/src/main/kotlin/cicada/cli/VoiceTests.kt@@ -0,0 +1,83 @@+// 读出来的声音 (Voices.kt): the Mac's catalog, default and fallback rules, and what goes to Ling.+// No network: LingClient runs against a fake transport.+package cicada.cli++import cicada.*+import java.io.ByteArrayInputStream++object VoiceTests {+ val tests: List<Pair<String, () -> Unit>> = listOf(+ "voiceCatalogIsTheMacs" to ::catalog,+ "voiceDefaultIsTheServicesFirstElseThePhones" to ::defaults,+ "voiceAChoiceTheServiceCantSpeakFallsBack" to ::fallback,+ "voiceChoicesSurviveARestart" to ::settingsRoundTrip,+ "voiceLingIsAskedForTheChosenVoice" to ::lingBody,+ )++ private fun check(ok: Boolean, what: String) { if (!ok) throw AssertionError(what) }+ private fun <T> equal(expected: T, actual: T, what: String) { if (expected != actual) throw AssertionError("$what: expected «$expected», got «$actual»") }++ private val ling = AppSettings().aiConfig()+ private val openrouter = AppSettings(aiProvider = "openrouter").aiConfig()++ fun catalog() {+ equal(listOf("ming:US_Emma", "ming:UK_George", "ming:UK_Charlotte", "phone"), VoiceCatalog.options("en", ling).map { it.id }, "English")+ equal(listOf("ming:灵小雅", "ming:灵小棠", "ming:灵小锋", "ming:灵卓然", "phone"), VoiceCatalog.options("zh-CN", ling).map { it.id }, "Chinese")+ equal(VoiceCatalog.options("zh-CN", ling), VoiceCatalog.options("zh-TW", ling), "one Chinese key")+ equal(listOf("ming:US_Emma", "ming:UK_George", "phone"), VoiceCatalog.options("ja", ling).map { it.id }, "Japanese")+ equal(listOf("phone"), VoiceCatalog.options("pt", ling).map { it.id }, "Portuguese: no Ming voice")+ equal("ja", VoiceCatalog.mingLanguage("ja"), "language_id")+ equal(null, VoiceCatalog.mingLanguage("zh-CN"), "Chinese needs none")+ equal(listOf("cloud:Kore", "cloud:Aoede", "cloud:Charon", "cloud:Puck", "phone"), VoiceCatalog.options("zh-CN", openrouter).map { it.id }, "Gemini's")+ val noVoice = AppSettings(aiProvider = "custom", aiCustomBase = "https://x.example/v1", aiModels = mutableMapOf("custom" to "m")).aiConfig()+ equal(listOf("phone"), VoiceCatalog.options("en", noVoice).map { it.id }, "no speech model")+ equal(listOf("女", "美式", "自然对话"), VoiceCatalog.ming("en")[0].tags, "tags are the Mac's keys")+ }++ fun defaults() {+ equal("ming:US_Emma", VoiceCatalog.defaultId("en", ling, speaks = true), "English")+ equal("ming:灵小雅", VoiceCatalog.defaultId("zh-CN", ling, speaks = true), "Chinese")+ equal("phone", VoiceCatalog.defaultId("en", ling, speaks = false), "no key")+ equal("phone", VoiceCatalog.defaultId("pt", ling, speaks = true), "no Ming voice")+ equal("cloud:Kore", VoiceCatalog.defaultId("en", openrouter, speaks = true), "OpenRouter")+ }++ fun fallback() {+ val chosen = mapOf("en" to "ming:UK_George", "zh" to "phone", "ja" to "ming:灵小雅")+ equal("ming:UK_George", VoiceCatalog.chosen(chosen, "en", ling, speaks = true), "kept")+ equal("phone", VoiceCatalog.chosen(chosen, "zh-CN", ling, speaks = true), "the phone's, chosen")+ equal("ming:US_Emma", VoiceCatalog.chosen(chosen, "ja", ling, speaks = true), "not one of Japanese's")+ equal("cloud:Kore", VoiceCatalog.chosen(chosen, "en", openrouter, speaks = true), "Ming after switching to OpenRouter")+ equal("ming:UK_George", VoiceCatalog.chosen(chosen, "en", ling, speaks = true), "and back with Ling")+ equal("phone", VoiceCatalog.chosen(chosen, "en", ling, speaks = false), "no key: the phone's")+ equal("ming:US_Emma", VoiceCatalog.chosen(emptyMap(), "en-US", ling, speaks = true), "never chosen")+ }++ fun settingsRoundTrip() {+ val s = AppSettings()+ s.speakVoices["en"] = "ming:UK_George"+ s.speakVoices["zh"] = "phone"+ s.save()+ equal(mapOf("en" to "ming:UK_George", "zh" to "phone"), AppSettings.load().speakVoices.toMap(), "speakVoices")+ check(Json.write(s.toJson()).contains("\"speakVoices\""), "the Mac's key")+ }++ fun lingBody() {+ val streamed = mutableListOf<String>()+ val fake = object : Transport {+ override fun send(url: String, method: String, body: String?, headers: Map<String, String>, timeoutMs: Int) = Transport.Response(200, "{}")+ override fun stream(url: String, body: String, headers: Map<String, String>, timeoutMs: Int): Transport.Stream {+ streamed.add(body)+ return Transport.Stream(200, "text/event-stream", ByteArrayInputStream("data: {\"type\": \"speech.audio.done\"}".toByteArray()))+ }+ }+ val s = AppSettings()+ val k = AIKey(PlainProtector, service = { s.aiProvider })+ k.remove(); k.save("sk-test-0000000000")+ val client = LingClient(k, fake, config = s::aiConfig)+ client.speech("こんにちは", voice = "UK_George", language = "ja") {}+ val b = Json.parse(streamed[0]).obj()!!+ equal(Triple("Ming-3.0-tts-0.5B", "UK_George", "ja"), Triple(b["model"], b["voice"], b["language_id"]), "Ming's voice and language")+ check("references" !in b, "no reference for a built-in voice")+ }+}diff --git a/android/core/src/main/kotlin/cicada/Settings.kt b/android/core/src/main/kotlin/cicada/Settings.ktindex 02c871d..87bedc5 100644--- a/android/core/src/main/kotlin/cicada/Settings.kt+++ b/android/core/src/main/kotlin/cicada/Settings.kt@@ -50,6 +50,9 @@ class AppSettings(var recordAudio: Boolean = true,/// 把我说的翻译给对方: 按住说话 in 面对面 (the Mac's 同声传译 switch).var speakBack: Boolean = true,+ /// 读出来的声音 per language key ("en", "zh"), as the Mac's speakVoices: "ming:US_Emma",+ /// "cloud:Kore", "phone". A language not in it uses VoiceCatalog.defaultId.+ var speakVoices: MutableMap<String, String> = mutableMapOf(),/// 会中改正听错的词: finished sentences carry the word list to the AI service, which points out/// misheard words (Correction). On by default; does nothing without an AI service.var fixMisheard: Boolean = true,@@ -91,7 +94,7 @@ class AppSettings("showInCapture" to showInCapture, "onboarded" to onboarded, "uiLanguage" to uiLanguage,"source" to source, "overlay" to overlay, "silenceEnd" to silenceEnd, "silenceMinutes" to silenceMinutes,"speakerVoices" to speakerVoices, "recordAudio" to recordAudio, "speakBack" to speakBack,- "fixMisheard" to fixMisheard, "askNames" to askNames,+ "speakVoices" to speakVoices.toSortedMap(), "fixMisheard" to fixMisheard, "askNames" to askNames,"exportOn" to exportOn, "exportFolder" to exportFolder, "exportName" to exportName,"updateLastChecked" to updateLastChecked, "updateNotified" to updateNotified,)@@ -129,7 +132,7 @@ class AppSettings(silenceEnd = o["silenceEnd"].str() ?: d.silenceEnd,silenceMinutes = (o["silenceMinutes"] as? Number)?.toDouble() ?: d.silenceMinutes,speakerVoices = o["speakerVoices"].bool() ?: true, recordAudio = o["recordAudio"].bool() ?: true,- speakBack = o["speakBack"].bool() ?: true,+ speakBack = o["speakBack"].bool() ?: true, speakVoices = strings(o["speakVoices"]),fixMisheard = o["fixMisheard"].bool() ?: true, askNames = o["askNames"].bool() ?: true,exportOn = o["exportOn"].bool() ?: false, exportFolder = o["exportFolder"].str() ?: "",exportName = o["exportName"].str() ?: "",diff --git a/android/core/src/main/kotlin/cicada/Voices.kt b/android/core/src/main/kotlin/cicada/Voices.ktnew file mode 100644index 0000000..46e2649--- /dev/null+++ b/android/core/src/main/kotlin/cicada/Voices.kt@@ -0,0 +1,83 @@+package cicada++/// A voice 我说 can read with (Voices.swift's VoiceOption): one of Ming's (through the Ling key), one+/// of another service's speech model, or the phone's text-to-speech. `id` is what settings keep:+/// "ming:US_Emma", "cloud:Kore", "phone".+data class VoiceOption(val id: String, val name: String, /** Chinese UI keys, localized where shown. */ val tags: List<String>)++/// Which voices to offer for each language the other side may hear (VoiceCatalog in Voices.swift).+/// Ming's are hand-picked natural ones; for languages it has no native voice for, Emma and George+/// speak it with `language_id`. The phone's own voice follows, so there is always one without a key.+object VoiceCatalog {+ const val PHONE = "phone"+ const val MING = "ming:"+ const val CLOUD = "cloud:"++ /// The picker's languages (key, title), as on the Mac. The key is the code without region.+ val languages = listOf("en" to "English", "zh" to "中文", "ja" to "日本語", "ko" to "한국어",+ "es" to "Español", "fr" to "Français", "de" to "Deutsch", "pt" to "Português")++ fun key(code: String): String = code.substringBefore('-').ifEmpty { "en" }++ fun title(code: String): String = languages.firstOrNull { it.first == key(code) }?.second ?: code++ /// Ming's `language_id` for languages that need it (zh and en work without).+ fun mingLanguage(code: String): String? = key(code).takeIf { it in listOf("ja", "ko", "de", "fr", "es") }++ fun ming(language: String): List<VoiceOption> {+ fun v(voice: String, name: String, vararg tags: String) = VoiceOption(MING + voice, name, tags.toList())+ return when (key(language)) {+ "en" -> listOf(v("US_Emma", "Emma", "女", "美式", "自然对话"), v("UK_George", "George", "男", "英式", "稳重"),+ v("UK_Charlotte", "Charlotte", "女", "英式", "平稳"))+ "zh" -> listOf(v("灵小雅", "小雅", "女", "清亮", "播报"), v("灵小棠", "小棠", "女", "温和", "沉稳"),+ v("灵小锋", "小锋", "男", "温暖", "亲切"), v("灵卓然", "卓然", "男", "沉着", "清楚"))+ "ja", "ko", "de", "fr", "es" -> listOf(v("US_Emma", "Emma", "女"), v("UK_George", "George", "男"))+ else -> emptyList()+ }+ }++ /// The service's own voices for a language: Ming's on Ling, a speech model's (the same in every+ /// language) elsewhere, none when it has no speech model.+ fun remote(language: String, config: AIConfig): List<VoiceOption> = when {+ !config.hasVoices -> emptyList()+ config.isLing -> ming(language)+ else -> config.voices.map { VoiceOption(CLOUD + it.id, it.id, listOf(it.gender).filter { g -> g.isNotEmpty() }) }+ }++ val phone = VoiceOption(PHONE, "手机的声音", listOf("本机"))++ fun options(language: String, config: AIConfig): List<VoiceOption> = remote(language, config) + phone++ /// What a language uses until the user picks: the service's first voice once it can speak,+ /// else the phone's (the Mac's defaultID).+ fun defaultId(language: String, config: AIConfig, speaks: Boolean): String =+ (if (speaks) remote(language, config).firstOrNull()?.id else null) ?: PHONE++ /// The chosen voice for a language, or its default (AppModel.voiceID): a choice the service in+ /// use can't speak (Ming after switching to OpenRouter, any after the key is gone) falls back+ /// to the default, and comes back with that service.+ fun chosen(voices: Map<String, String>, language: String, config: AIConfig, speaks: Boolean): String {+ val fallback = defaultId(language, config, speaks)+ val id = voices[key(language)] ?: return fallback+ return when {+ id == PHONE -> id+ speaks && remote(language, config).any { it.id == id } -> id+ else -> fallback+ }+ }++ fun option(id: String, language: String, config: AIConfig): VoiceOption? =+ options(language, config).firstOrNull { it.id == id }++ /// A short line to try a voice with, in the language it will speak.+ fun sample(language: String): String = when (key(language)) {+ "zh" -> "谢谢大家。我们来看一下上线时间表,并确定谁负责麦克风测试。"+ "ja" -> "皆さん、ありがとうございます。発売スケジュールを確認しましょう。"+ "ko" -> "감사합니다. 출시 일정을 함께 확인해 보겠습니다."+ "es" -> "Gracias a todos. Revisemos el calendario de lanzamiento."+ "fr" -> "Merci à tous. Regardons ensemble le calendrier de lancement."+ "de" -> "Danke an alle. Schauen wir uns den Zeitplan für den Start an."+ "pt" -> "Obrigado a todos. Vamos ver o cronograma de lançamento."+ else -> "Thanks everyone. Let's look at the launch timeline and decide who owns the microphone tests."+ }+}