知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
feat(android): In person can read your translated words in your own voice, cloned from a 10–15 s recording with a Ling key
wquguru3a993c00c041
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex ab12b3e..5b58e77 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -49,6 +49,7 @@<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=".VoiceRecordActivity" android:exported="false" android:parentActivityName=".VoicesActivity" /><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/App.kt b/android/app/src/main/kotlin/com/wquguru/cicada/App.ktindex 793d85b..101766f 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/App.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/App.kt@@ -30,6 +30,7 @@ import cicada.SpeakerTaggerimport cicada.Stringsimport cicada.Translatorimport cicada.VoiceCatalog+import cicada.VoiceReferenceimport cicada.Wavimport java.io.Fileimport java.util.Locale@@ -255,12 +256,38 @@ 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+ fun voiceId(lang: String): String =+ VoiceCatalog.chosen(settings.speakVoices, lang, ling.config(), ling.speaks, ling.clones && VoiceReference.exists)++ /// 用这个声音: keeps the recording and uses it for `lang` (the language the picker was on).+ fun saveVoiceReference(pcm: ShortArray, text: String, lang: String): Boolean = try {+ VoiceReference.save(pcm, text)+ Log.d("voice clone saved ${pcm.size / 16000} s")+ settings.speakVoices[VoiceCatalog.key(lang)] = VoiceCatalog.CLONE+ saveSettings()+ true+ } catch (e: Exception) { Log.d("voice clone save failed ${e.javaClass.simpleName}"); false }++ /// 删除: the recording goes, and every language that used it is back on its default.+ fun removeVoiceReference() {+ VoiceReference.remove()+ settings.speakVoices.entries.removeAll { it.value == VoiceCatalog.CLONE }+ saveSettings()+ Log.d("voice clone removed")+ }++ /// Reads `text` in a service voice id (not the phone's): Ming's or Gemini's by name, or the+ /// user's own cloned from the saved recording. Failed when it can't (the caller falls back).+ private fun speakIn(id: String, text: String, lang: String, onStart: () -> Unit, onEnd: () -> Unit,+ draft: Pair<String, String>? = null): Voice.Result {+ if (id == VoiceCatalog.CLONE) {+ val ref = draft ?: VoiceReference.reference()+ if (ref == null || !ling.clones) { onEnd(); return Voice.Result.Failed }+ return voice.speakCloud(ling, text, null, VoiceCatalog.mingLanguage(lang), onStart, onEnd, reference = ref)+ }+ return if (id.startsWith(VoiceCatalog.MING)) voice.speakCloud(ling, text, id.removePrefix(VoiceCatalog.MING), VoiceCatalog.mingLanguage(lang), onStart, onEnd)+ else voice.speakCloud(ling, text, id.removePrefix(VoiceCatalog.CLOUD), null, onStart, onEnd)+ }/// 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.@@ -270,10 +297,10 @@ class CicadaApp : Application() {listen.muted = truechanged()val id = voiceId(lang)+ Log.d("voice: $lang in $id")if (id != VoiceCatalog.PHONE) {background.execute {- val (name, language) = cloudArgs(id, lang)- val r = voice.speakCloud(ling, text, name, language, onStart = { changed() }, onEnd = {})+ val r = speakIn(id, text, lang, onStart = { changed() }, onEnd = {})if (r == Voice.Result.Spoken) main.postDelayed({ if (!voice.speaking) { listen.muted = false; changed() } }, 400)else speakWithPhone(text, lang)}@@ -286,8 +313,10 @@ class CicadaApp : Application() {@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 = {}) {+ /// line, so nothing is muted. `draft`: a recording not saved yet, for the clone (录好了).+ /// `failed` comes on the main thread with why nothing played.+ fun previewVoice(id: String, lang: String, text: String = VoiceCatalog.sample(lang), draft: Pair<String, String>? = null,+ failed: (String) -> Unit = {}) {voice.stop()previewing = idchanged()@@ -303,8 +332,7 @@ class CicadaApp : Application() {return}background.execute {- val (name, language) = cloudArgs(id, lang)- val r = voice.speakCloud(ling, text, name, language, onStart = {}, onEnd = { done() })+ val r = speakIn(id, text, lang, onStart = {}, onEnd = { done() }, draft = draft)Log.d("voice: preview $id $lang ${r.name}")if (r != Voice.Result.Spoken) main.post { failed(Strings.L("没能读出来")) }}diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.ktindex 12eff7c..1ec5553 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/DebugReceiver.kt@@ -9,6 +9,7 @@ import cicada.Stringsimport cicada.Logimport cicada.Sessionimport cicada.VoiceCatalog+import cicada.VoiceReferenceimport cicada.Wavimport java.io.Fileimport java.util.concurrent.CountDownLatch@@ -25,6 +26,7 @@ import java.util.concurrent.TimeUnit/// 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]+/// voiceref <wav in files/> [lang] | remove (我自己的声音 from a pushed recording) · show record-voice <lang> [<wav in files/>]/// 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>@@ -141,7 +143,24 @@ class DebugReceiver : BroadcastReceiver() {if (id.isEmpty()) app.settings.speakVoices.remove(VoiceCatalog.key(lang)) else app.settings.speakVoices[VoiceCatalog.key(lang)] = idapp.saveSettings()}- return mapOf("lang" to lang, "voice" to app.voiceId(lang), "options" to VoiceCatalog.options(lang, app.ling.config()).map { it.id })+ return mapOf("lang" to lang, "voice" to app.voiceId(lang), "options" to VoiceCatalog.options(lang, app.ling.config()).map { it.id },+ "clone" to VoiceReference.exists, "cloneSeconds" to VoiceReference.duration, "clones" to app.ling.clones)+ }+ // 我自己的声音 without a microphone: `voiceref <wav in files/> [<lang>]` checks a pushed+ // recording as 录制 would (Ming hears it) and saves it for <lang>; `voiceref remove` is 删除.+ // Replies with numbers only (never what it says).+ "voiceref" -> {+ if (arg == "remove") { app.removeVoiceReference(); return mapOf("exists" to VoiceReference.exists) }+ val name = arg.substringBefore(' ')+ val lang = arg.substringAfter(' ', "en")+ val pcm = Wav.read(File(app.filesDir, name).inputStream())+ app.background.execute {+ when (val r = VoiceReference.check(app.translator, pcm, app.settings.targetCode)) {+ is VoiceReference.Check.Ok -> app.main.post { Log.d("debug: voiceref saved=${app.saveVoiceReference(pcm, r.text, lang)}") }+ is VoiceReference.Check.Again -> Log.d("debug: voiceref refused: ${Strings.LF(r.reason, *r.args.toTypedArray())}")+ }+ }+ return mapOf("seconds" to pcm.size / 16000.toDouble(), "checking" to true)}"voice-preview" -> {val words = arg.split(Regex("\\s+"), 2)@@ -258,6 +277,12 @@ class DebugReceiver : BroadcastReceiver() {"words" -> open(WordListActivity::class.java)"ai" -> open(AiServiceActivity::class.java)"voices" -> open(VoicesActivity::class.java, arg.substringAfter(' ', "").ifEmpty { null })+ // `show record <lang> [<wav in files/>]`: 录制 for that language; a WAV stands in for the mic.+ "record-voice" -> {+ val rest = arg.substringAfter(' ', "").split(' ')+ app.startActivity(Intent(app, VoiceRecordActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ .putExtra("id", rest[0].ifEmpty { "en" }).apply { rest.getOrNull(1)?.let { putExtra("wav", it) } })+ }"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 fbd064f..8c13640 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/SettingsActivity.kt@@ -96,7 +96,11 @@ class SettingsActivity : Activity() {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),+ ui.listRow(L("试一句"), when (english?.id) {+ null, VoiceCatalog.PHONE -> L("用手机的声音读一句英语")+ VoiceCatalog.CLONE -> L("用你的声音读一句英语")+ else -> Strings.LF("用 %@ 的声音读一句英语", english.name)+ },trailing = ui.icon(R.drawable.i_play, 20, Palette.ink), chevron = false) { tryVoice() })))page.addView(ui.sectionLabel(L("在其他应用上")))diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt b/android/app/src/main/kotlin/com/wquguru/cicada/Voice.ktindex a5915d4..5166678 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/Voice.kt@@ -70,12 +70,13 @@ class Voice(private val context: Context) {private class Stopped : RuntimeException()@Volatile private var track: AudioTrack? = null- /// 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.+ /// Reads `text` in the AI service's `voiceName` (Ming's with `language`, Ming's language_id), or+ /// in the user's own voice cloned from `reference`: 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 {+ onStart: () -> Unit, onEnd: () -> Unit, reference: Pair<String, String>? = null): Result {val rate = LingClient.TTS_RATEval t = try {AudioTrack.Builder()@@ -91,7 +92,7 @@ class Voice(private val context: Context) {speaking = truevar frames = 0Ltry {- ling.speech(text, voiceName, language) { pcm ->+ ling.speech(text, voiceName, language, reference = reference) { 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/VoiceRecordActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/VoiceRecordActivity.ktnew file mode 100644index 0000000..32f78a6--- /dev/null+++ b/android/app/src/main/kotlin/com/wquguru/cicada/VoiceRecordActivity.kt@@ -0,0 +1,296 @@+package com.wquguru.cicada++import android.Manifest+import android.app.Activity+import android.content.Intent+import android.content.pm.PackageManager+import android.content.res.ColorStateList+import android.graphics.Color+import android.media.AudioAttributes+import android.media.AudioFormat+import android.media.AudioRecord+import android.media.AudioTrack+import android.media.MediaRecorder+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.Log+import cicada.Segmenter+import cicada.Strings+import cicada.Strings.L+import cicada.VoiceCatalog+import cicada.VoiceReference+import cicada.Wav+import java.io.File+import kotlin.concurrent.thread++/// 我自己的声音: the Mac's VoiceCloneSheet as a page. Read a passage for 10–15 s → Ming writes down+/// what it says → listen to the recording and to the clone → 用这个声音 keeps it (VoiceReference)+/// and picks it for the language the picker was on (`id`). Nothing is kept until then.+class VoiceRecordActivity : Activity() {+ private enum class Phase { Idle, Recording, Checking, Ready, Failed }++ private lateinit var ui: Ui+ private lateinit var page: LinearLayout+ private lateinit var language: String+ private var phase = Phase.Idle+ private var problem = ""+ private var seconds = 0.0+ @Volatile private var pcm = ShortArray(0)+ private var transcript = ""+ @Volatile private var record: AudioRecord? = null+ private var player: AudioTrack? = null+ private var playingOriginal = false+ private var unobserve: (() -> Unit)? = null++ /// My language: the passage is in it, and it decides 最像你 / 会带你的口音.+ private val own get() = cicada.settings.targetCode++ 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(24), 0, ui.dp(24), ui.dp(32)) }+ setContentView(ui.screen(this, null, back = true, ground = Palette.card, body = page))+ // Debug (`show record <wav in files/>`): a pushed WAV stands in for the microphone.+ intent.getStringExtra("wav")?.let { name ->+ try { pcm = Wav.read(File(filesDir, name).inputStream()); seconds = pcm.size / Segmenter.RATE.toDouble(); phase = Phase.Recording; finishRecording(); return } catch (e: Exception) { Log.d("voice clone: no ${e.javaClass.simpleName}") }+ }+ build()+ }++ override fun onResume() { super.onResume(); unobserve = cicada.observe { if (phase == Phase.Ready) build() } }+ override fun onPause() { super.onPause(); unobserve?.invoke(); unobserve = null }++ override fun onDestroy() {+ super.onDestroy()+ stopRecorder()+ stopPlayer()+ }++ private fun build() {+ page.removeAllViews()+ if (phase == Phase.Ready) review() else recording()+ }++ // MARK: Reading the passage++ private fun recording() {+ page.addView(ui.title(L("录制你的声音")))+ page.addView(ui.helper(L("请用平时开会的自然语气朗读以下段落,约 15 秒,在安静环境下录制效果最佳。")).apply { leading(1.5f) }, ui.lp(top = 10))+ page.addView(ui.text(VoiceReference.passage(own), 17f, Palette.ink).apply {+ leading(1.75f)+ background = ui.rounded(Palette.ground, 16)+ setPadding(ui.dp(18), ui.dp(16), ui.dp(18), ui.dp(16))+ }, ui.lp(top = 18))+ page.addView(ui.helper(L("这是我自己的声音。只在我说话时用它替我翻译。"), Palette.tertiary), ui.lp(top = 12))++ val clock = ui.text("%d:%02d".format(seconds.toInt() / 60, seconds.toInt() % 60), 32f, Palette.ink).apply { gravity = Gravity.CENTER }+ val bar = ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal).apply {+ max = (VoiceReference.MAX_SECONDS * 10).toInt()+ progress = (seconds * 10).toInt()+ progressTintList = ColorStateList.valueOf(Palette.accent)+ progressBackgroundTintList = ColorStateList.valueOf(Palette.divider)+ }+ val range = ui.helper(Strings.LF("%lld–%lld 秒", VoiceReference.MIN_SECONDS.toInt(), VoiceReference.MAX_SECONDS.toInt()), Palette.tertiary).apply { gravity = Gravity.CENTER }+ clockView = clock; barView = bar+ page.addView(clock, ui.lp(top = 36))+ page.addView(bar,LinearLayout.LayoutParams(ui.dp(240), ui.dp(6)).apply { topMargin = ui.dp(10); gravity = Gravity.CENTER_HORIZONTAL })+ page.addView(range, ui.lp(top = 8))++ when (phase) {+ Phase.Checking -> page.addView(ui.row(10,+ ProgressBar(this, null, android.R.attr.progressBarStyleSmall).apply { indeterminateTintList = ColorStateList.valueOf(Palette.accent) },+ ui.helper(L("正在听写…"))).apply { gravity = Gravity.CENTER }, ui.lp(top = 28))+ else -> {+ if (phase == Phase.Failed) page.addView(ui.text(problem, 14f, Palette.link).apply { gravity = Gravity.CENTER }, ui.lp(top = 20))+ val label = when (phase) { Phase.Recording -> L("读完了"); Phase.Failed -> L("再录一次"); else -> L("开始录") }+ page.addView(recordButton(label), LinearLayout.LayoutParams(ui.dp(88), ui.dp(88)).apply { topMargin = ui.dp(20); gravity = Gravity.CENTER_HORIZONTAL })+ page.addView(ui.helper(label).apply { gravity = Gravity.CENTER; importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO }, ui.lp(top = 10))+ }+ }+ }++ /// The big round button: a mic to start, a square to finish.+ private fun recordButton(label: String) = FrameLayout(this).apply {+ contentDescription = label+ background = ui.rounded(Palette.accentPale, 44)+ val inner = FrameLayout(context).apply { background = ui.rounded(Palette.accent, 32) }+ if (phase == Phase.Recording) inner.addView(View(context).apply { background = ui.rounded(Color.WHITE, 4) }, FrameLayout.LayoutParams(ui.dp(22), ui.dp(22), Gravity.CENTER))+ else inner.addView(ui.icon(R.drawable.i_mic, 28, Color.WHITE), FrameLayout.LayoutParams(ui.dp(28), ui.dp(28), Gravity.CENTER))+ addView(inner, FrameLayout.LayoutParams(ui.dp(64), ui.dp(64), Gravity.CENTER))+ ui.tappable(this, 44, background) { if (phase == Phase.Recording) finishRecording() else startRecording() }+ }++ private fun startRecording() {+ if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {+ requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 1)+ return+ }+ stopPlayer()+ val rate = Segmenter.RATE+ val size = maxOf(AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT), rate)+ val r = try {+ AudioRecord.Builder().setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION)+ .setAudioFormat(AudioFormat.Builder().setSampleRate(rate).setEncoding(AudioFormat.ENCODING_PCM_16BIT).setChannelMask(AudioFormat.CHANNEL_IN_MONO).build())+ .setBufferSizeInBytes(size).build().also { it.startRecording() }+ } catch (e: Exception) { Log.d("voice clone: mic ${e.javaClass.simpleName}"); null }+ if (r == null || r.recordingState != AudioRecord.RECORDSTATE_RECORDING) {+ r?.release()+ phase = Phase.Failed; problem = L("麦克风没收到声音,请检查麦克风权限"); build(); return+ }+ record = r+ pcm = ShortArray(0); seconds = 0.0; phase = Phase.Recording+ val max = (VoiceReference.MAX_SECONDS * rate).toInt()+ thread(name = "VoiceRecord", isDaemon = true) {+ val all = ShortArray(max)+ var n = 0+ val chunk = ShortArray(rate / 10)+ while (record === r && n < max) {+ val got = r.read(chunk, 0, minOf(chunk.size, max - n))+ if (got <= 0) break+ System.arraycopy(chunk, 0, all, n, got)+ n += got+ pcm = all.copyOf(n)+ }+ }+ tick()+ build()+ }++ private var clockView: android.widget.TextView? = null+ private var barView: ProgressBar? = null++ /// The clock, 10 times a second; at 15 s the recording finishes by itself. Only the clock and+ /// bar change: rebuilding the page would drop a tap on 读完了 halfway through.+ private fun tick() {+ if (phase != Phase.Recording || isDestroyed) return+ seconds = pcm.size / Segmenter.RATE.toDouble()+ if (seconds >= VoiceReference.MAX_SECONDS - 0.05) { finishRecording(); return }+ clockView?.text = "%d:%02d".format(seconds.toInt() / 60, seconds.toInt() % 60)+ barView?.progress = (seconds * 10).toInt()+ cicada.main.postDelayed(::tick, 100)+ }++ private fun stopRecorder() {+ val r = record ?: return+ record = null+ try { r.stop() } catch (_: Exception) {}+ r.release()+ }++ /// Stops, then the Mac's checks: long enough, heard, not read too slowly.+ private fun finishRecording() {+ if (phase != Phase.Recording) return+ stopRecorder()+ val clip = pcm+ seconds = clip.size / Segmenter.RATE.toDouble()+ phase = Phase.Checking+ build()+ val app = cicada+ app.background.execute {+ val result = VoiceReference.check(app.translator, clip, own)+ app.main.post {+ if (isDestroyed) return@post+ when (result) {+ is VoiceReference.Check.Ok -> { transcript = result.text; phase = Phase.Ready }+ is VoiceReference.Check.Again -> { problem = Strings.LF(result.reason, *result.args.toTypedArray()); phase = Phase.Failed }+ }+ build()+ }+ }+ }++ // MARK: Listening back++ private fun review() {+ val app = cicada+ page.addView(ui.title(L("录好了,先听听像不像")))+ page.addView(ui.helper(Strings.LF("%lld 秒 · 识别出的文字会与录音一起用于学习你的音色", Math.round(seconds).toInt())).apply { leading(1.5f) }, ui.lp(top = 10))+ val original = clipRow(playingOriginal, false, L("你的原声"), transcript, null) { playOriginal() }+ val clone = clipRow(app.previewing == DRAFT, true, Strings.LF("用你的声音说%@", VoiceCatalog.title(language)), VoiceCatalog.sample(language), L("对方会听到这个")) {+ if (!app.ling.clones) return@clipRow+ stopPlayer()+ app.previewVoice(DRAFT, language, draft = draft(), failed = { android.widget.Toast.makeText(this, it, android.widget.Toast.LENGTH_SHORT).show() })+ }+ clone.background = ui.rounded(Palette.accentPale, 0)+ page.addView(ui.group(listOf(original, clone), radius = 16).apply { background = ui.rounded(Palette.card, 16, stroke = Palette.line) }, ui.lp(top = 20))+ if (!app.ling.clones) page.addView(ui.text(L("需先在“AI 服务”中填入 Ling key,才能使用你自己的声音。"), 13f, Palette.link), ui.lp(top = 12))+ page.addView(ui.helper(L("听起来不像或有杂音?换个安静的地方重录一次。录音只存在这台手机上,可随时删除。"), Palette.tertiary).apply { leading(1.5f) }, ui.lp(top = 14))+ page.addView(ui.button(L("用这个声音")) { save() }.apply { if (!app.ling.clones) alpha = 0.5f }, ui.lp(top = 32))+ page.addView(ui.button(L("重录"), kind = "quiet") { stopPlayer(); phase = Phase.Idle; seconds = 0.0; build() }, ui.lp(top = 10))+ }++ private fun draft(): Pair<String, String> =+ "data:audio/wav;base64," + java.util.Base64.getEncoder().encodeToString(Wav.bytes(pcm)) to transcript++ private fun clipRow(playing: Boolean, accent: Boolean, title: String, detail: String, tag: String?, play: () -> Unit): View {+ val button = FrameLayout(this).apply {+ contentDescription = title+ background = ui.rounded(if (accent) Palette.accent else Palette.ground, 22)+ if (playing) addView(ProgressBar(context, null, android.R.attr.progressBarStyleSmall).apply {+ indeterminateTintList = ColorStateList.valueOf(if (accent) Color.WHITE else Palette.accent)+ }, FrameLayout.LayoutParams(ui.dp(20), ui.dp(20), Gravity.CENTER))+ else addView(ui.icon(R.drawable.i_play, 18, if (accent) Color.WHITE else Palette.ink), FrameLayout.LayoutParams(ui.dp(18), ui.dp(18), Gravity.CENTER))+ ui.tappable(this, 22, background) { play() }+ }+ val texts = ui.stack(3, ui.text(title, 15f, Palette.ink, bold = true))+ if (tag != null) texts.addView(ui.text(tag, 12f, Palette.link))+ texts.addView(ui.text(detail, 13f, Palette.secondary).apply { leading(1.5f) })+ return LinearLayout(this).apply {+ orientation = LinearLayout.HORIZONTAL+ setPadding(ui.dp(16), ui.dp(16), ui.dp(16), ui.dp(16))+ addView(button, LinearLayout.LayoutParams(ui.dp(44), ui.dp(44)).apply { rightMargin = ui.dp(14) })+ addView(texts, ui.weight())+ }+ }++ private fun playOriginal() {+ if (playingOriginal) { stopPlayer(); build(); return }+ cicada.voice.stop()+ val clip = pcm+ val t = try {+ AudioTrack.Builder()+ .setAudioAttributes(AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build())+ .setAudioFormat(AudioFormat.Builder().setSampleRate(Segmenter.RATE).setEncoding(AudioFormat.ENCODING_PCM_16BIT).setChannelMask(AudioFormat.CHANNEL_OUT_MONO).build())+ .setTransferMode(AudioTrack.MODE_STATIC).setBufferSizeInBytes(clip.size * 2).build()+ } catch (_: Exception) { return }+ t.write(clip, 0, clip.size)+ t.notificationMarkerPosition = clip.size+ t.setPlaybackPositionUpdateListener(object : AudioTrack.OnPlaybackPositionUpdateListener {+ override fun onMarkerReached(track: AudioTrack) { stopPlayer(); if (!isDestroyed) build() }+ override fun onPeriodicNotification(track: AudioTrack) {}+ })+ player = t+ playingOriginal = true+ t.play()+ build()+ }++ private fun stopPlayer() {+ player?.let { try { it.stop() } catch (_: Exception) {}; it.release() }+ player = null+ playingOriginal = false+ }++ private fun save() {+ val app = cicada+ if (!app.ling.clones) { startActivity(Intent(this, AiServiceActivity::class.java)); return }+ stopPlayer()+ if (app.saveVoiceReference(pcm, transcript, language)) finish()+ }++ @Deprecated("Deprecated in Java")+ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {+ if (grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) startRecording()+ else { phase = Phase.Failed; problem = L("麦克风没收到声音,请检查麦克风权限"); build() }+ }++ companion object {+ /// previewVoice's id while the unsaved recording is tried.+ const val DRAFT = VoiceCatalog.CLONE+ }+}diff --git a/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.kt b/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.ktindex 10fa674..22b7013 100644--- a/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.kt+++ b/android/app/src/main/kotlin/com/wquguru/cicada/VoicesActivity.kt@@ -15,6 +15,7 @@ import cicada.Stringsimport cicada.Strings.Limport cicada.VoiceCatalogimport cicada.VoiceOption+import cicada.VoiceReference/// 读出来的声音 (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@@ -44,7 +45,8 @@ class VoicesActivity : Activity() {val app = cicadaval ling = app.lingval chosen = app.voiceId(language)- val key = listOf(language, chosen, app.previewing, ling.keyState, ling.provider.id, ling.speaks, app.settings.speakVoices, Strings.language).joinToString("|")+ val key = listOf(language, chosen, app.previewing, ling.keyState, ling.provider.id, ling.speaks, app.settings.speakVoices, Strings.language,+ VoiceReference.exists, VoiceReference.audio.lastModified()).joinToString("|")if (key == shown) returnshown = keypage.removeAllViews()@@ -57,7 +59,7 @@ class VoicesActivity : Activity() {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) }+ val rows = VoiceCatalog.options(language, ling.config()).map { voiceRow(it, chosen) } + cloneRow(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) })}@@ -94,6 +96,78 @@ class VoicesActivity : Activity() {return row}+ /// 我自己的声音, last (the Mac's cloneRow): only Ling clones, so another service offers 去换成 Ling;+ /// without a recording, 录制; with one, 试听, how it was recorded, 重录 · 删除, and the radio.+ private fun cloneRow(chosen: String): View {+ val app = cicada+ val ling = app.ling+ if (!ling.provider.clones) {+ return ui.listRow(L("我自己的声音"), L("只有 Ling 能用你自己的声音"),+ trailing = smallButton(L("去换成 Ling"), primary = false) { startActivity(Intent(this, AiServiceActivity::class.java)) },+ chevron = false, titleView = ui.text(L("我自己的声音"), 16f, Palette.secondary, lines = 1))+ }+ fun record() = startActivity(Intent(this, VoiceRecordActivity::class.java).putExtra("id", language))+ if (!VoiceReference.exists) {+ val mic = FrameLayout(this).apply {+ background = ui.rounded(Palette.accentPale, 18)+ addView(ui.icon(R.drawable.i_mic, 18, Palette.link), FrameLayout.LayoutParams(ui.dp(18), ui.dp(18), Gravity.CENTER))+ layoutParams = LinearLayout.LayoutParams(ui.dp(36), ui.dp(36))+ }+ return ui.listRow(L("我自己的声音"), L("录 15 秒原声,对方听到你的音色,晚约 3 秒"), leading = mic,+ trailing = smallButton(L("录制"), primary = true, enabled = ling.clones) { if (ling.clones) record() },+ chevron = false, titleView = ui.text(L("我自己的声音"), 16f, Palette.ink, bold = true, lines = 1)) { if (ling.clones) record() }+ }+ val selected = chosen == VoiceCatalog.CLONE+ val own = VoiceCatalog.key(app.settings.targetCode) == VoiceCatalog.key(language)+ val note = if (VoiceReference.savedIsSlow) L("读得偏慢") else if (own) L("最像你") else L("会带你的口音")+ // The Mac's one line, as two: 重录 · 删除 don't fit beside it on a phone in English.+ val links = ui.row(0,+ link(L("重录")) { record() },+ ui.text(" · ", 13f, Palette.secondary),+ link(L("删除")) {+ // A small link on a phone: asked first, unlike the Mac.+ ui.confirm(this, L("删除"), L("我自己的声音"), L("删除"), destructive = true) { app.removeVoiceReference(); shown = null; build() }+ })+ val texts = ui.stack(2, ui.text(L("我自己的声音"), 16f, Palette.ink, bold = true, lines = 1),+ ui.text(Strings.LF("已录 %lld 秒 · %@", Math.round(VoiceReference.duration).toInt(), note), 13f, Palette.secondary), links)+ val row = LinearLayout(this).apply {+ orientation = LinearLayout.HORIZONTAL+ gravity = Gravity.CENTER_VERTICAL+ minimumHeight = ui.dp(56)+ setPadding(ui.dp(16), ui.dp(12), ui.dp(16), ui.dp(12))+ addView(playButton(VoiceCatalog.CLONE, selected, ling.clones), LinearLayout.LayoutParams(ui.dp(36), ui.dp(36)).apply { rightMargin = ui.dp(14) })+ addView(texts, ui.weight())+ addView(radio(selected), LinearLayout.LayoutParams(ui.dp(20), ui.dp(20)).apply { leftMargin = ui.dp(10) })+ contentDescription = L("用我自己的声音")+ isSelected = selected+ ui.tappable(this, 0, if (selected) GradientDrawable().apply { setColor(Palette.accentPale) } else null) {+ if (!ling.clones) return@tappable+ app.settings.speakVoices[VoiceCatalog.key(language)] = VoiceCatalog.CLONE+ app.saveSettings()+ shown = null; build()+ }+ }+ if (!ling.clones) row.alpha = 0.5f+ return row+ }++ private fun link(label: String, onClick: () -> Unit) = ui.text(label, 13f, Palette.link, bold = true, lines = 1).apply {+ paintFlags = paintFlags or android.graphics.Paint.UNDERLINE_TEXT_FLAG+ setPadding(0, ui.dp(6), 0, ui.dp(6))+ contentDescription = label+ ui.tappable(this, 6) { onClick() }+ }++ private fun smallButton(label: String, primary: Boolean, enabled: Boolean = true, onClick: () -> Unit) =+ ui.text(label, 14f, if (primary) Color.WHITE else Palette.ink, bold = true, lines = 1).apply {+ gravity = Gravity.CENTER+ minHeight = ui.dp(36)+ setPadding(ui.dp(14), 0, ui.dp(14), 0)+ contentDescription = label+ if (!enabled) alpha = 0.5f+ ui.tappable(this, 18, ui.rounded(if (primary) Palette.ink else Palette.card, 18, stroke = if (primary) null else Palette.line), dark = primary) { onClick() }+ }+/// 试听: 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@@ -129,7 +203,7 @@ class VoicesActivity : Activity() {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+ fun name(v: VoiceOption): String = if (v.id == VoiceCatalog.PHONE || v.id == VoiceCatalog.CLONE) L(v.name) else v.name/// "女 · 美式 · Ming" / "本机 · 最快": who it is and where it comes from.fun summary(v: VoiceOption): String = when {diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xmlindex 427fc96..1c4220e 100644--- a/android/app/src/main/res/xml/data_extraction_rules.xml+++ b/android/app/src/main/res/xml/data_extraction_rules.xml@@ -12,6 +12,8 @@</cloud-backup><device-transfer><exclude domain="file" path="ling-api-key" />+ <!-- 我自己的声音: the recording of the user's voice stays on this phone. -->+ <exclude domain="file" path="voice" /><!-- 分享…: this phone's share identity and the links' manage tokens stay on this phone. --><exclude domain="file" path="share-device.json" /><exclude domain="file" path="Shares" />diff --git a/android/app/src/main/strings/en.lproj/Android.strings b/android/app/src/main/strings/en.lproj/Android.stringsindex d76a7ba..b1a1cc5 100644--- a/android/app/src/main/strings/en.lproj/Android.strings+++ b/android/app/src/main/strings/en.lproj/Android.strings@@ -231,3 +231,5 @@"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";+"用你的声音读一句英语" = "Hear an English sentence in your own voice";+"听起来不像或有杂音?换个安静的地方重录一次。录音只存在这台手机上,可随时删除。" = "Doesn't sound like you, or noisy? Record again somewhere quiet. The recording stays on this phone and can be deleted anytime.";diff --git a/android/app/src/main/strings/ja.lproj/Android.strings b/android/app/src/main/strings/ja.lproj/Android.stringsindex af80ada..ef63330 100644--- a/android/app/src/main/strings/ja.lproj/Android.strings+++ b/android/app/src/main/strings/ja.lproj/Android.strings@@ -231,3 +231,5 @@"Ling 不可用时自动换成手机的声音" = "Ling が使えないときはスマホの声に切り替え";"%@ 用不了时,自动换手机的声音" = "%@ が使えないときはスマホの声に切り替え";"这个服务不出声音,用手机的声音" = "このサービスは声が出ないため、スマホの声を使用";+"用你的声音读一句英语" = "自分の声で英語を1文聞く";+"听起来不像或有杂音?换个安静的地方重录一次。录音只存在这台手机上,可随时删除。" = "似ていない、またはノイズがありますか?静かな場所で録り直してください。録音はこのスマホにだけ保存され、いつでも削除できます。";diff --git a/android/app/src/main/strings/ko.lproj/Android.strings b/android/app/src/main/strings/ko.lproj/Android.stringsindex b407a02..5331b82 100644--- a/android/app/src/main/strings/ko.lproj/Android.strings+++ b/android/app/src/main/strings/ko.lproj/Android.strings@@ -231,3 +231,5 @@"Ling 不可用时自动换成手机的声音" = "Ling을 쓸 수 없으면 휴대전화 음성으로 전환";"%@ 用不了时,自动换手机的声音" = "%@을(를) 쓸 수 없으면 휴대전화 음성으로 전환";"这个服务不出声音,用手机的声音" = "이 서비스는 음성이 없어 휴대전화 음성 사용";+"用你的声音读一句英语" = "내 목소리로 영어 한 문장 듣기";+"听起来不像或有杂音?换个安静的地方重录一次。录音只存在这台手机上,可随时删除。" = "내 목소리 같지 않거나 잡음이 있나요? 조용한 곳에서 다시 녹음해 보세요. 녹음은 이 휴대전화에만 저장되며 언제든 삭제할 수 있습니다.";diff --git a/android/cli/src/main/kotlin/cicada/cli/Main.kt b/android/cli/src/main/kotlin/cicada/cli/Main.ktindex 6d59428..01a6f40 100644--- a/android/cli/src/main/kotlin/cicada/cli/Main.kt+++ b/android/cli/src/main/kotlin/cicada/cli/Main.kt@@ -8,6 +8,7 @@// 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+// --reference <wav> [--own zh-CN]: in the voice of that recording (我自己的声音), checked first// cicada-cli segments <file.wav> where the segmenter cuts// cicada-cli roundtrip <session.json>… reads and writes records, says if a byte changed//@@ -117,10 +118,18 @@ fun main(argv: Array<String>) {val ling = client(settings())val voice = opt("--voice", "").ifEmpty { null }val lang = opt("--lang", "").ifEmpty { null }+ // --reference <wav> [--own zh-CN]: the user's own voice, the recording checked as 录制 checks it.+ val reference = opt("--reference", "").ifEmpty { null }?.let { path ->+ val pcm = Wav.read(File(path).inputStream())+ when (val r = VoiceReference.check(Translator(ling), pcm, opt("--own", "zh-CN"))) {+ is VoiceReference.Check.Ok -> { println("reference: %.1f s, heard %d characters".format(pcm.size / 16000.0, r.text.length)); "data:audio/wav;base64," + java.util.Base64.getEncoder().encodeToString(Wav.bytes(pcm)) to r.text }+ is VoiceReference.Check.Again -> { println("reference refused: ${Strings.LF(r.reason, *r.args.toTypedArray())}"); exitProcess(1) }+ }+ }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) }+ ling.speech(args[1], voice, lang, reference = reference) { 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"))diff --git a/android/cli/src/main/kotlin/cicada/cli/VoiceTests.kt b/android/cli/src/main/kotlin/cicada/cli/VoiceTests.ktindex f5c498e..f44ede0 100644--- a/android/cli/src/main/kotlin/cicada/cli/VoiceTests.kt+++ b/android/cli/src/main/kotlin/cicada/cli/VoiceTests.kt@@ -12,8 +12,119 @@ object VoiceTests {"voiceAChoiceTheServiceCantSpeakFallsBack" to ::fallback,"voiceChoicesSurviveARestart" to ::settingsRoundTrip,"voiceLingIsAskedForTheChosenVoice" to ::lingBody,+ "cloneOnlyWithLingAndARecording" to ::cloneFallback,+ "cloneSendsTheRecordingAsAReference" to ::cloneBody,+ "cloneIsRefusedByOtherServices" to ::cloneElsewhere,+ "cloneRecordingIsKeptPrivatelyAndRemoved" to ::storage,+ "clonePaceIsTheMacs" to ::pace,+ "cloneRecordingIsCheckedLikeTheMac" to ::checkRecording,)+ private class Fake(val reply: String = "{}") : Transport {+ val streamed = mutableListOf<Pair<String, Int>>()+ val sent = mutableListOf<String>()+ override fun send(url: String, method: String, body: String?, headers: Map<String, String>, timeoutMs: Int): Transport.Response {+ sent.add(body ?: ""); return Transport.Response(200, reply)+ }+ override fun stream(url: String, body: String, headers: Map<String, String>, timeoutMs: Int): Transport.Stream {+ streamed.add(body to timeoutMs)+ val chunk = java.util.Base64.getEncoder().encodeToString(byteArrayOf(1, 0))+ return Transport.Stream(200, "text/event-stream", ByteArrayInputStream("data: {\"audio\": \"$chunk\"}\ndata: {\"type\": \"speech.audio.done\"}".toByteArray()))+ }+ }++ private fun client(fake: Transport, s: AppSettings): LingClient {+ val k = AIKey(PlainProtector, service = { s.aiProvider })+ k.remove(); k.save("sk-test-0000000000")+ return LingClient(k, fake, config = s::aiConfig)+ }++ /// A tone at 16 kHz: `seconds` long, silence before and after.+ private fun tone(seconds: Double, pad: Double = 0.5): ShortArray {+ val rate = Segmenter.RATE+ val out = ShortArray(((seconds + 2 * pad) * rate).toInt())+ val from = (pad * rate).toInt()+ for (i in 0 until (seconds * rate).toInt()) out[from + i] = (8000 * kotlin.math.sin(2 * Math.PI * 220 * i / rate)).toInt().toShort()+ return out+ }++ fun cloneFallback() {+ val chosen = mapOf("en" to "clone")+ equal("clone", VoiceCatalog.chosen(chosen, "en", ling, speaks = true, canClone = true), "kept")+ equal("ming:US_Emma", VoiceCatalog.chosen(chosen, "en", ling, speaks = true, canClone = false), "no recording")+ equal("cloud:Kore", VoiceCatalog.chosen(chosen, "en", openrouter, speaks = true, canClone = false), "OpenRouter can't clone")+ equal("phone", VoiceCatalog.chosen(chosen, "en", ling, speaks = false, canClone = false), "no key")+ equal("我自己的声音", VoiceCatalog.option("clone", "en", ling)?.name, "its name")+ check(Providers.LING.clones && !Providers.OPENROUTER.clones, "only Ling clones")+ }++ fun cloneBody() {+ val fake = Fake()+ val c = client(fake, AppSettings())+ check(c.clones, "Ling with a key clones")+ val got = java.io.ByteArrayOutputStream()+ c.speech("Bonjour", language = "fr", reference = "data:audio/wav;base64,UklGRg==" to "大家好") { got.write(it) }+ val (body, timeout) = fake.streamed[0]+ val b = Json.parse(body).obj()!!+ equal(listOf(mapOf("audio" to "data:audio/wav;base64,UklGRg==", "text" to "大家好")), b["references"], "references")+ check("voice" !in b, "no built-in voice with a reference")+ equal("fr", b["language_id"], "language_id")+ check(timeout >= 30_000, "30 s for a clone, got $timeout")+ equal(2, got.size(), "audio came")+ }++ fun cloneElsewhere() {+ val fake = Fake()+ val c = client(fake, AppSettings(aiProvider = "openrouter"))+ check(!c.clones, "OpenRouter doesn't clone")+ try { c.speech("Hi", reference = "data:audio/wav;base64,AA==" to "hi") {}; throw AssertionError("spoke") } catch (_: LingException) {}+ equal(0, fake.streamed.size, "nothing sent")+ }++ fun storage() {+ VoiceReference.remove()+ check(!VoiceReference.exists && VoiceReference.reference() == null, "none yet")+ val pcm = tone(12.0, pad = 0.0)+ VoiceReference.save(pcm, "大家好,我是主持人。")+ check(VoiceReference.exists, "saved")+ equal(12L, Math.round(VoiceReference.duration), "duration")+ val (audio, text) = VoiceReference.reference()!!+ check(audio.startsWith("data:audio/wav;base64,UklGR"), "a WAV data URI")+ equal("大家好,我是主持人。", text, "its text")+ equal(pcm.toList(), Wav.read(VoiceReference.audio.inputStream()).toList(), "16 kHz as recorded")+ val perms = java.nio.file.Files.getPosixFilePermissions(VoiceReference.audio.toPath()).map { it.name }.toSet()+ equal(setOf("OWNER_READ", "OWNER_WRITE"), perms, "owner only")+ equal(VoiceReference.folder, VoiceReference.audio.parentFile, "in voice/")+ VoiceReference.remove()+ check(!VoiceReference.exists && !VoiceReference.folder.exists(), "removed")+ }++ fun pace() {+ equal(listOf("大", "家", "hello", "it's", "2026"), VoiceReference.tokens("大家 Hello, it’s 2026!"), "tokens")+ val span = VoiceReference.speechSpan(tone(4.0))!!+ check(kotlin.math.abs(span - 4.0) < 0.05, "speech span $span")+ equal(null, VoiceReference.speechSpan(ShortArray(16000)), "silence")+ check(VoiceReference.isSlow("大家好我是主持人", 2.0), "2 characters a second is slow")+ check(!VoiceReference.isSlow("大家好我是主持人", 4.0), "4 is not")+ check(VoiceReference.isSlow("hello everyone thanks for joining", 1.2), "1.2 words a second is slow")+ check(!VoiceReference.isSlow("hello everyone thanks for joining", 2.5), "2.5 is not")+ }++ fun checkRecording() {+ fun heard(original: String) = Fake(Json.write(mapOf("choices" to listOf(mapOf(+ "message" to mapOf("content" to "LANG: zh-CN\nORIGINAL: $original\nTRANSLATION: Hello everyone."), "finish_reason" to "stop"))), pretty = false))+ val short = VoiceReference.check(Translator(client(heard("大家好"), AppSettings())), tone(8.0, pad = 0.0), "zh-CN")+ equal(VoiceReference.Check.Again("录音太短了,请至少朗读 %lld 秒", listOf(10)), short, "under 10 s")+ // 12 s read as 12 characters: one a second, too slow for a meeting.+ val slow = VoiceReference.check(Translator(client(heard("大家好我是这次会议的主持人"), AppSettings())), tone(12.0), "zh-CN")+ equal(VoiceReference.Check.Again("读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次"), slow, "slow")+ val passage = "大家好,我是这次会议的主持人。今天我们主要讨论新产品的上线计划,包括时间安排、测试范围和市场推广。"+ val ok = VoiceReference.check(Translator(client(heard(passage), AppSettings())), tone(11.0), "zh-CN")+ equal(VoiceReference.Check.Ok(passage), ok, "heard at an ordinary pace")+ val none = VoiceReference.check(Translator(client(heard("嗯"), AppSettings())), tone(11.0), "zh-CN")+ equal(VoiceReference.Check.Again("没听清录音内容,请换个安静的地方再录一次"), none, "nothing heard")+ }+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»") }diff --git a/android/core/src/main/kotlin/cicada/Ling.kt b/android/core/src/main/kotlin/cicada/Ling.ktindex a833cf2..80a4591 100644--- a/android/core/src/main/kotlin/cicada/Ling.kt+++ b/android/core/src/main/kotlin/cicada/Ling.kt@@ -284,6 +284,8 @@ class LingClient(val usable get() = hasKey && keyState != KeyState.Invalid/// The service's own voice reads my words to the other side (otherwise the phone's voice).val speaks get() = usable && config().hasVoices+ /// The user's own voice: only Ling clones.+ val clones get() = speaks && config().provider.clones/// Whether the hear model takes audio: false once it refused (a check or a meeting), true once/// it heard, null until then (always true on Ling: Ming).val hears: Boolean? get() = when (val s = aiCheck[AICheck.StepID.Hear]) {@@ -737,12 +739,15 @@ class LingClient(/// The service's voice for `text`, handed to `onPcm` as raw 24 kHz mono 16-bit PCM while it/// arrives. `voice` is one of the service's (another, e.g. a Ming name, becomes its first);- /// `language` is Ming's language_id, Ling only. Replies come three ways and all are read:- /// server-sent base64 chunks (Ling, ZenMux), raw PCM (OpenRouter), or one JSON `{"audio": <WAV>}`.- fun speech(text: String, voice: String? = null, language: String? = null, timeout: Double = 20.0, onPcm: (ByteArray) -> Unit) {+ /// `language` is Ming's language_id, Ling only; `reference` (a WAV data URI and what it says,+ /// VoiceReference) clones the user's voice instead, Ling only. Replies come three ways and all+ /// are read: server-sent base64 chunks (Ling, ZenMux), raw PCM (OpenRouter), or one JSON+ /// `{"audio": <WAV>}`.+ fun speech(text: String, voice: String? = null, language: String? = null, timeout: Double = 20.0,+ reference: Pair<String, String>? = null, onPcm: (ByteArray) -> Unit) {// The voice isn't part of a check (it costs money): its real outcome is what 现在能用的 says.try {- speak(text, voice, language, timeout, onPcm)+ speak(text, voice, language, if (reference != null) maxOf(timeout, 30.0) else timeout, reference, onPcm)lastVoice = true to System.currentTimeMillis(); changed()} catch (e: LingException) {lastVoice = false to System.currentTimeMillis(); changed()@@ -751,14 +756,19 @@ class LingClient(// Anything else came from onPcm: the phone stopped it on purpose, not a failure.}- private fun speak(text: String, voice: String?, language: String?, timeout: Double, onPcm: (ByteArray) -> Unit) {+ private fun speak(text: String, voice: String?, language: String?, timeout: Double, reference: Pair<String, String>?, onPcm: (ByteArray) -> Unit) {val k = currentKey() ?: throw LingException(LingException.Kind.NoKey)val c = config()val voiceBase = c.voiceBaseif (!c.hasVoices || voiceBase == null) throw LingException(LingException.Kind.NoKey)+ // Only Ling clones: elsewhere a reference would read in someone else's voice, so refuse+ // and let the caller fall back.+ if (reference != null && !c.provider.clones) throw LingException(LingException.Kind.NoKey)val body = linkedMapOf<String, Any?>("model" to c.voiceModel, "input" to text, "response_format" to "pcm")if (c.isLing) {- body.putAll(mapOf("sample_rate" to TTS_RATE, "stream" to true, "stream_format" to "sse", "voice" to (voice ?: "UK_Charlotte")))+ body.putAll(mapOf("sample_rate" to TTS_RATE, "stream" to true, "stream_format" to "sse"))+ if (reference != null) body["references"] = listOf(mapOf("audio" to reference.first, "text" to reference.second))+ else body["voice"] = voice ?: "UK_Charlotte"if (language != null) body["language_id"] = language} else {// OpenRouter documents no `stream` (it streams the bytes anyway); ZenMux needs it.diff --git a/android/core/src/main/kotlin/cicada/VoiceReference.kt b/android/core/src/main/kotlin/cicada/VoiceReference.ktnew file mode 100644index 0000000..2fea6ca--- /dev/null+++ b/android/core/src/main/kotlin/cicada/VoiceReference.kt@@ -0,0 +1,150 @@+package cicada++import java.io.File+import java.util.Base64+import kotlin.math.sqrt++/// The recording Ming clones the user's voice from (VoiceReference in Voices.swift): `voice/reference.wav`+/// (16 kHz mono) and `voice/reference.txt` (what it says, as Ming heard it) in the app's private+/// folder, kept out of backups and device transfer. Never leaves the phone except inside a speech+/// request to Ling; never in records, exports or the log.+object VoiceReference {+ /// The phones' limits (#32): every sentence sends the clip again, so a long one makes the voice+ /// late. The Mac allows 8–30 s.+ const val MIN_SECONDS = 10.0+ const val MAX_SECONDS = 15.0++ val folder get() = File(Paths.root, "voice")+ val audio get() = File(folder, "reference.wav")+ val textFile get() = File(folder, "reference.txt")++ val text: String? get() = try { textFile.readText().takeIf { it.isNotBlank() } } catch (_: Exception) { null }+ val exists: Boolean get() = audio.isFile && text != null++ val duration: Double get() = try { (audio.length() - 44).coerceAtLeast(0) / 2.0 / Segmenter.RATE } catch (_: Exception) { 0.0 }++ /// What Ming needs: the clip as a data URI and its transcript.+ fun reference(): Pair<String, String>? {+ val t = text ?: return null+ val bytes = try { audio.readBytes() } catch (_: Exception) { return null }+ return "data:audio/wav;base64," + Base64.getEncoder().encodeToString(bytes) to t+ }++ fun save(pcm: ShortArray, text: String) {+ folder.mkdirs()+ folder.setReadable(false, false); folder.setReadable(true, true)+ folder.setExecutable(false, false); folder.setExecutable(true, true)+ val tmp = File(folder, "reference.wav.tmp")+ tmp.writeBytes(Wav.bytes(pcm))+ if (!tmp.renameTo(audio)) { audio.delete(); tmp.renameTo(audio) }+ textFile.writeText(text)+ for (f in listOf(audio, textFile)) { f.setReadable(false, false); f.setReadable(true, true); f.setWritable(false, false); f.setWritable(true, true) }+ cachedSlow = null+ }++ fun remove() { folder.deleteRecursively(); cachedSlow = null }++ // MARK: Pace (the Mac's)++ /// Ming copies the recording's pace into every sentence. Below these (characters for Chinese,+ /// Japanese and Korean, words otherwise, per second of speech) the clone is too slow for a+ /// meeting; reading the passage at an ordinary pace gives 3.5–5 and 2.3–3.+ const val SLOW_CHARACTERS = 2.5+ const val SLOW_WORDS = 1.6++ /// SpeakScore.tokens: each CJK character, and each run of letters, digits and apostrophes.+ fun tokens(text: String): List<String> {+ val out = mutableListOf<String>()+ val word = StringBuilder()+ fun flush() { if (word.isNotEmpty()) { out.add(word.toString().lowercase()); word.clear() } }+ var i = 0+ while (i < text.length) {+ val cp = text.codePointAt(i)+ when {+ isCJK(cp) -> { flush(); out.add(String(Character.toChars(cp))) }+ Character.isLetterOrDigit(cp) || cp == '\''.code || cp == '’'.code -> word.appendCodePoint(if (cp == '’'.code) '\''.code else cp)+ else -> flush()+ }+ i += Character.charCount(cp)+ }+ flush()+ return out+ }++ fun isCJK(cp: Int) = cp in 0x3040..0x30FF || cp in 0x3400..0x4DBF || cp in 0x4E00..0x9FFF || cp in 0xAC00..0xD7AF || cp in 0xF900..0xFAFF++ /// Seconds from the first to the last 20 ms window within 35 dB of the loudest one.+ fun speechSpan(samples: ShortArray, rate: Int = Segmenter.RATE): Double? {+ val size = maxOf(1, (rate * 0.02).toInt())+ val levels = ArrayList<Double>()+ var i = 0+ while (i < samples.size) {+ val end = minOf(samples.size, i + size)+ var sum = 0.0+ for (k in i until end) { val s = samples[k] / 32768.0; sum += s * s }+ levels.add(sqrt(sum / (end - i)))+ i = end+ }+ val loudest = levels.maxOrNull() ?: return null+ if (loudest <= 0.003) return null+ val floor = loudest * 0.0178+ val first = levels.indexOfFirst { it >= floor }+ val last = levels.indexOfLast { it >= floor }+ if (first < 0) return null+ return (last - first + 1) * size.toDouble() / rate+ }++ /// Characters or words a second, silence at both ends left out; null when there is no speech.+ fun pace(text: String, samples: ShortArray, rate: Int = Segmenter.RATE): Double? {+ val units = tokens(text).size+ val span = speechSpan(samples, rate) ?: return null+ if (units == 0 || span <= 0.5) return null+ return units / span+ }++ fun isSlow(text: String, pace: Double): Boolean {+ val t = tokens(text)+ val characters = t.count { w -> w.codePoints().anyMatch(::isCJK) }+ return pace < (if (characters * 2 >= t.size) SLOW_CHARACTERS else SLOW_WORDS)+ }++ @Volatile private var cachedSlow: Pair<Long, Boolean>? = null++ /// The saved recording is read too slowly (worked out once per recording).+ val savedIsSlow: Boolean get() {+ val t = text ?: return false+ val stamp = audio.lastModified()+ cachedSlow?.let { if (it.first == stamp) return it.second }+ val slow = try { pace(t, Wav.read(audio.inputStream()))?.let { isSlow(t, it) } ?: false } catch (_: Exception) { false }+ cachedSlow = stamp to slow+ return slow+ }++ /// The passage to read, in the user's own language.+ fun passage(language: String): String = when (VoiceCatalog.key(language)) {+ "zh" -> "大家好,我是这次会议的主持人。今天我们主要讨论新产品的上线计划,包括时间安排、测试范围和市场推广。请大家先看一下屏幕上的议程。"+ "ja" -> "皆さん、こんにちは。今日の会議では、新製品の発売計画について話し合います。スケジュール、テストの範囲、そしてマーケティングについて順番に確認しましょう。"+ else -> "Hello everyone, thanks for joining. Today we'll walk through the launch plan for the new product: the schedule, what we still need to test, and how we'll tell people about it. Let's start with the agenda on the screen."+ }++ /// What the recording says, as the service hears it (the Mac transcribes on the device; the+ /// phone has Ming), then checked as the Mac checks it. Returns the text, or the reason to+ /// record again (a Chinese UI key).+ sealed class Check {+ data class Ok(val text: String) : Check()+ data class Again(val reason: String, val args: List<Any> = emptyList()) : Check()+ }++ fun check(translator: Translator, pcm: ShortArray, own: String): Check {+ val seconds = pcm.size / Segmenter.RATE.toDouble()+ if (seconds < MIN_SECONDS) return Check.Again("录音太短了,请至少朗读 %lld 秒", listOf(MIN_SECONDS.toInt()))+ val other = if (VoiceCatalog.key(own) == "en") "zh-CN" else "en"+ val heard = try { translator.hear(Clip.wav(pcm), other, own, seconds) } catch (e: Exception) { Log.d("voice clone: hear failed ${e.javaClass.simpleName}"); null }+ val text = heard?.original?.trim().orEmpty()+ if (text.length < 6) return Check.Again("没听清录音内容,请换个安静的地方再录一次")+ val pace = pace(text, pcm)+ Log.d("voice clone: ${text.length} chars, pace ${pace?.let { "%.1f".format(it) } ?: "-"}/s")+ if (pace != null && isSlow(text, pace)) return Check.Again("读得有点慢,克隆的声音也会这么慢。请用平时说话的语速再录一次")+ return Check.Ok(text)+ }+}diff --git a/android/core/src/main/kotlin/cicada/Voices.kt b/android/core/src/main/kotlin/cicada/Voices.ktindex 46e2649..26b916a 100644--- a/android/core/src/main/kotlin/cicada/Voices.kt+++ b/android/core/src/main/kotlin/cicada/Voices.kt@@ -1,8 +1,9 @@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".+/// of another service's speech model, the phone's text-to-speech, or the user's own voice cloned+/// from a recording (VoiceReference). `id` is what settings keep: "ming:US_Emma", "cloud:Kore",+/// "phone", "clone".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).@@ -10,6 +11,7 @@ data class VoiceOption(val id: String, val name: String, /** Chinese UI keys, lo/// 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 CLONE = "clone"const val MING = "ming:"const val CLOUD = "cloud:"@@ -45,6 +47,7 @@ object VoiceCatalog {}val phone = VoiceOption(PHONE, "手机的声音", listOf("本机"))+ val clone = VoiceOption(CLONE, "我自己的声音", emptyList())fun options(language: String, config: AIConfig): List<VoiceOption> = remote(language, config) + phone@@ -54,20 +57,22 @@ object VoiceCatalog {(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 {+ /// use can't speak (Ming after switching to OpenRouter, any after the key is gone, the user's+ /// own voice without Ling or without a recording: `canClone`) falls back to the default, and+ /// comes back with that service.+ fun chosen(voices: Map<String, String>, language: String, config: AIConfig, speaks: Boolean, canClone: Boolean = false): String {val fallback = defaultId(language, config, speaks)val id = voices[key(language)] ?: return fallbackreturn when {id == PHONE -> id+ id == CLONE -> if (canClone) id else fallbackspeaks && remote(language, config).any { it.id == id } -> idelse -> fallback}}fun option(id: String, language: String, config: AIConfig): VoiceOption? =- options(language, config).firstOrNull { it.id == id }+ if (id == CLONE) clone else 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)) {