AnyBot/src/voice.rs

358 lines
15 KiB
Rust
Raw Normal View History

Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
// 語音 on this device: only recording from the microphone and playing sound. What was said is
// turned into text, and answers into sound, by the brain's voice service (speech.rs), the same
// for every screen and the phone. macOS records with its own AVAudioRecorder (through osascript,
// no extra install); elsewhere cpal does (mic.rs).
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
/// Longest recording (estimated; the recorder script also stops itself at 10 minutes).
pub const MAX_SECS: u64 = 600;
/// 會議記錄 can run longer: two hours stays under the transcription service's 25 MB limit at this
/// recorder's bitrate (estimated).
pub const MEETING_MAX_SECS: u64 = 7_200;
Bug sweep: gates, relay 2FA, Windows input, snapshots, encodings Permissions and reach - a file leaving a computer passes the same questions as reading it; "looking" shell commands that do more than look ask first - a symlink out of the work/sealed folder counts as outside it (real paths, not just lexical ones); the search walk skips links - web_fetch and skill_install read the public web only: localhost, the LAN and cloud metadata are refused, at every redirect - preview shows a file without running it; browser_upload may ask - vault: logins no longer match across shared suffixes (pages.dev, com.tw, ...); registrable_domain knows public suffixes - axwrite: found elements are retained (use-after-free) Relay - replacing or turning off 2FA needs the current code (rate-limited); new recovery codes only count once enrollment is verified - a removed computer loses its socket and its `call` access - a site name taken by another account answers 409 - RELAY_TRUST_PROXY: the login lock counts the caller's address, not the proxy's (compose files and README) - httpd: half a body is not a request Desktop - sign-in, join and restore work with 2FA on (code field; --serve reads ANYBOT_ACCOUNT_CODE; the setup wizard points to a pairing code) - Windows: text was typed twice; modifiers are held through click, drag and scroll; horizontal scroll; screen control is no longer refused - a recording that hits the limit is transcribed, not thrown away - bot's computer: a new home volume restores the snapshot; a snapshot is read through before the home is wiped; a failed volume removal stops reset/restore - events of a stopped turn no longer land in the next one; each channel message gets a turn of its own - saving a bot's settings keeps what it got meanwhile (three-way merge); a save file that cannot be read is kept - pages in Big5/GBK/Shift_JIS are read in their own encoding (encoding_rs); osascript output past 64 KB no longer stalls - pick_tab keeps a job's own non-http tab; pictures larger than the texture limit are fitted; the auto-update time field takes typing - skills live in <data>/skills; memories are unnumbered in the prompt; the phone may skillify and skill_install CI - the test step fails when the tests fail (it piped into tail) Tests: anybot 268 passed, 27 ignored; relay 16 passed; clippy unchanged. Not run: Windows on a real machine (win.rs type-checked alone), the Docker paths of the bot's computer, the live accessibility writes. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-10 03:46:17 +00:00
/// A recording limit in words (「10 分鐘」, 「2 小時」).
pub fn length_words(secs: u64) -> String {
if secs >= 3600 && secs.is_multiple_of(3600) {
format!("{} 小時", secs / 3600)
} else {
format!("{} 分鐘", secs / 60)
}
}
const RECORDER: &str = r#"ObjC.import('AVFoundation');
ObjC.import('Foundation');
function run(argv) {
const url = $.NSURL.fileURLWithPath(argv[0]);
const settings = $.NSDictionary.dictionaryWithObjectsForKeys(
[$.NSNumber.numberWithInt(1633772320), $.NSNumber.numberWithDouble(16000.0), $.NSNumber.numberWithInt(1)],
[$('AVFormatIDKey'), $('AVSampleRateKey'), $('AVNumberOfChannelsKey')]);
const rec = $.AVAudioRecorder.alloc.initWithURLSettingsError(url, settings, null);
if (rec.isNil()) return 'fail';
if (!rec.record) return 'denied';
const fm = $.NSFileManager.defaultManager;
for (let i = 0; i < 72000; i++) { if (fm.fileExistsAtPath(argv[1])) break; delay(0.1); }
rec.stop;
return 'ok';
}"#;
/// 通話模式: listens until the person stops talking (AVAudioRecorder metering).
/// Speech is louder than SPEECH_DB; SILENCE_TICKS × 0.1 s of quiet after speech ends a turn;
/// nothing heard for WAIT_TICKS × 0.1 s gives up (all estimated).
const SPEECH_DB: f64 = -38.0;
const SILENCE_TICKS: u32 = 12;
const WAIT_TICKS: u32 = 300;
const LISTENER: &str = r#"ObjC.import('AVFoundation');
ObjC.import('Foundation');
function run(argv) {
const url = $.NSURL.fileURLWithPath(argv[0]);
const settings = $.NSDictionary.dictionaryWithObjectsForKeys(
[$.NSNumber.numberWithInt(1633772320), $.NSNumber.numberWithDouble(16000.0), $.NSNumber.numberWithInt(1)],
[$('AVFormatIDKey'), $('AVSampleRateKey'), $('AVNumberOfChannelsKey')]);
const rec = $.AVAudioRecorder.alloc.initWithURLSettingsError(url, settings, null);
if (rec.isNil()) return 'fail';
rec.meteringEnabled = true;
if (!rec.record) return 'denied';
const fm = $.NSFileManager.defaultManager;
const speech = Number(argv[2]), quietMax = Number(argv[3]), waitMax = Number(argv[4]);
let heard = false, quiet = 0;
for (let i = 0; i < 6000; i++) {
if (fm.fileExistsAtPath(argv[1])) break;
delay(0.1);
rec.updateMeters;
const p = rec.averagePowerForChannel(0);
if (p > speech) { heard = true; quiet = 0; } else if (heard) { quiet++; }
if (heard && quiet >= quietMax) break;
if (!heard && i >= waitMax) { rec.stop; return 'nothing'; }
}
rec.stop;
return heard ? 'ok' : 'nothing';
}"#;
/// The recorder: macOS's AVAudioRecorder script, or cpal (mic.rs) elsewhere.
enum Rec {
Script(Child),
Mic(crate::mic::Recorder),
}
pub struct Recording {
rec: Rec,
pub file: PathBuf,
stop: PathBuf,
pub started: Instant,
}
pub fn start() -> Result<Recording, String> {
if !cfg!(target_os = "macos") {
let file = std::env::temp_dir().join(format!("anybot-voice-{}-{}.wav", std::process::id(), chrono::Utc::now().timestamp_millis()));
let rec = crate::mic::start(file.clone(), None, MEETING_MAX_SECS);
return Ok(Recording { rec: Rec::Mic(rec), stop: file.with_extension("stop"), file, started: Instant::now() });
}
let base = std::env::temp_dir().join(format!("anybot-voice-{}-{}", std::process::id(), chrono::Utc::now().timestamp_millis()));
let file = base.with_extension("m4a");
let stop = base.with_extension("stop");
let child = Command::new("osascript")
.args(["-l", "JavaScript", "-e", RECORDER, "--"])
.arg(&file)
.arg(&stop)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("無法開始錄音:{e}"))?;
Ok(Recording { rec: Rec::Script(child), file, stop, started: Instant::now() })
}
/// Listen for one spoken turn: stops by itself when the person goes quiet.
pub fn listen() -> Result<Recording, String> {
if !cfg!(target_os = "macos") {
let file = std::env::temp_dir().join(format!("anybot-call-{}-{}.wav", std::process::id(), chrono::Utc::now().timestamp_millis()));
let rec = crate::mic::start(file.clone(), Some(crate::mic::Listen { speech_db: SPEECH_DB, quiet_ticks: SILENCE_TICKS, wait_ticks: WAIT_TICKS }), MAX_SECS);
return Ok(Recording { rec: Rec::Mic(rec), stop: file.with_extension("stop"), file, started: Instant::now() });
}
let base = std::env::temp_dir().join(format!("anybot-call-{}-{}", std::process::id(), chrono::Utc::now().timestamp_millis()));
let (file, stop) = (base.with_extension("m4a"), base.with_extension("stop"));
let child = Command::new("osascript")
.args(["-l", "JavaScript", "-e", LISTENER, "--"])
.arg(&file)
.arg(&stop)
.args([SPEECH_DB.to_string(), SILENCE_TICKS.to_string(), WAIT_TICKS.to_string()])
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.map_err(|e| format!("無法開始聽:{e}"))?;
Ok(Recording { rec: Rec::Script(child), file, stop, started: Instant::now() })
}
impl Recording {
/// The listener stopped by itself (the person finished, or nobody spoke).
pub fn done(&mut self) -> bool {
match &mut self.rec {
Rec::Script(c) => matches!(c.try_wait(), Ok(Some(_))),
Rec::Mic(m) => m.done(),
}
}
/// Stop and give back the audio file.
pub fn finish(mut self) -> Result<PathBuf, String> {
let child = match &mut self.rec {
Rec::Script(c) => c,
Rec::Mic(m) => {
return match m.finish() {
Some("fail") => Err("找不到可以用的麥克風。".into()),
Some("nothing") => Err("沒有聽到說話。".into()),
None => Err("錄音沒有正常結束。".into()),
Some(_) if std::fs::metadata(&self.file).map(|m| m.len() > 4000).unwrap_or(false) => Ok(self.file.clone()),
Some(_) => Err("沒有錄到聲音。".into()),
};
}
};
let _ = std::fs::write(&self.stop, b"");
let t = Instant::now();
let status = loop {
if let Ok(Some(_)) = child.try_wait() {
break true;
}
if t.elapsed() > Duration::from_secs(4) {
let _ = child.kill();
break false;
}
std::thread::sleep(Duration::from_millis(50));
};
let _ = std::fs::remove_file(&self.stop);
let mut said = String::new();
if let Some(mut o) = child.stdout.take() {
use std::io::Read;
let _ = o.read_to_string(&mut said);
}
match said.trim() {
"denied" => {
let _ = crate::computer::spawn_reaped(Command::new("open").arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone"));
Err("macOS 還沒讓 AnyBot 使用麥克風。我已經打開「系統設定 → 隱私權與安全性 → 麥克風」:把 AnyBot(或「終端機」)打開,再試一次。".into())
}
"fail" => Err("找不到可以用的麥克風。".into()),
"nothing" => Err("沒有聽到說話。".into()),
_ if !status => Err("錄音沒有正常結束。".into()),
_ => {
let ok = std::fs::metadata(&self.file).map(|m| m.len() > 1000).unwrap_or(false);
if ok {
Ok(self.file.clone())
} else {
Err("沒有錄到聲音。".into())
}
}
}
}
pub fn cancel(mut self) {
let _ = std::fs::write(&self.stop, b"");
match &mut self.rec {
Rec::Script(c) => {
std::thread::sleep(Duration::from_millis(300));
let _ = c.kill();
}
Rec::Mic(m) => {
let _ = m.finish();
}
}
let _ = std::fs::remove_file(&self.stop);
let _ = std::fs::remove_file(&self.file);
}
}
/// The spoken languages offered for voice chat (the original: 語言 Auto-detect…): (code, name).
pub const SPOKEN: [(&str, &str); 6] = [("", "自動偵測"), ("zh", "中文"), ("en", "English"), ("ja", "日本語"), ("ko", "한국어"), ("es", "Español")];
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
/// The speeds offered (the original: 速度 1x…).
pub const SPEEDS: [f32; 5] = [0.75, 1.0, 1.25, 1.5, 2.0];
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
// ---------- 播放 ----------
/// Each `say` gets a number; a newer one (or `stop_speaking`) makes the older one stop.
static PLAY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
static PLAYING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Get the sound (`fetch`: from the brain) and play it, instead of whatever was playing. What
/// goes wrong lands in `note`. `speaking()` is true from now until it has finished.
pub fn say(fetch: impl FnOnce() -> Result<Vec<u8>, String> + Send + 'static, note: std::sync::Arc<std::sync::Mutex<Option<String>>>) {
use std::sync::atomic::Ordering::SeqCst;
let gen = PLAY_GEN.fetch_add(1, SeqCst) + 1;
PLAYING.store(true, SeqCst);
std::thread::spawn(move || {
let r = fetch().and_then(|mp3| if PLAY_GEN.load(SeqCst) == gen { play(mp3, gen) } else { Ok(()) });
if PLAY_GEN.load(SeqCst) == gen {
if let Err(e) = r {
*note.lock().unwrap() = Some(e);
}
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
PLAYING.store(false, SeqCst);
}
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
});
}
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
/// MP3 out of the speakers, until it ends or a newer `say` / `stop_speaking` comes.
fn play(mp3: Vec<u8>, gen: u64) -> Result<(), String> {
use std::sync::atomic::Ordering::SeqCst;
let mut sink = rodio::DeviceSinkBuilder::open_default_sink().map_err(|_| "找不到可以播放聲音的裝置".to_string())?;
sink.log_on_drop(false);
let dec = rodio::Decoder::new(std::io::Cursor::new(mp3)).map_err(|_| "語音服務傳回的聲音放不出來".to_string())?;
let player = rodio::Player::connect_new(sink.mixer());
player.append(dec);
while !player.empty() {
if PLAY_GEN.load(SeqCst) != gen {
player.stop();
break;
}
std::thread::sleep(Duration::from_millis(50));
}
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
Ok(())
}
// ---------- 提示音 ----------
/// 提示音: two soft bell notes going up (E6, then A6 0.16 s later), about 0.8 s, quiet. Made
/// here instead of shipped as a file, so it sounds the same on macOS, Windows and Linux.
pub fn chime_samples(rate: u32) -> Vec<f32> {
let r = rate as f32;
let len = (r * 0.8) as usize;
let mut out = vec![0.0f32; len];
let tau = std::f32::consts::TAU;
for (freq, start) in [(1318.51f32, 0.0f32), (1760.0, 0.16)] {
let s0 = (start * r) as usize;
for (i, o) in out.iter_mut().enumerate().skip(s0) {
let t = (i - s0) as f32 / r;
// 4 ms to full, then a bell's fall; a softer octave above gives it its ring.
let env = (t / 0.004).min(1.0) * (-t * 7.0).exp();
*o += 0.16 * env * ((tau * freq * t).sin() + 0.3 * (-t * 5.0).exp() * (tau * 2.0 * freq * t).sin());
}
}
// The last 20 ms down to nothing (no click when the sound stops).
let tail = (r * 0.02) as usize;
for k in 0..tail {
out[len - 1 - k] *= k as f32 / tail as f32;
}
out
}
/// Ring the 提示音 once, without waiting. Several requests at once ring once (2 s apart at most).
pub fn chime() {
static LAST: std::sync::Mutex<Option<Instant>> = std::sync::Mutex::new(None);
{
let mut last = LAST.lock().unwrap();
if last.is_some_and(|t| t.elapsed() < Duration::from_secs(2)) {
return;
}
*last = Some(Instant::now());
}
std::thread::spawn(|| {
let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else { return };
sink.log_on_drop(false);
const RATE: u32 = 44_100;
let player = rodio::Player::connect_new(sink.mixer());
player.append(rodio::buffer::SamplesBuffer::new(std::num::NonZero::new(1).unwrap(), std::num::NonZero::new(RATE).unwrap(), chime_samples(RATE)));
player.sleep_until_end();
});
}
pub fn stop_speaking() {
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
use std::sync::atomic::Ordering::SeqCst;
PLAY_GEN.fetch_add(1, SeqCst);
PLAYING.store(false, SeqCst);
}
pub fn speaking() -> bool {
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
PLAYING.load(std::sync::atomic::Ordering::SeqCst)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
Voice: its own 設定 › 語音, run by the brain for every screen and the phone Voice was three implementations that broke on their own: speech to text borrowed the OpenAI key (so with only Grok set up the mic recorded, then failed), OpenAI's models it hard-coded stop on 2027-02-26, read aloud was macOS `say` or espeak-ng (silently nothing on Windows, where espeak isn't installed), and the phone used the browser's own recognition. Now: - 設定 › 語音 has 聽 and 說, each a service: off, OpenAI-compatible (OpenAI, Groq, a Whisper server of your own: the address decides), xAI or ElevenLabs. An empty key borrows 設定 › 模型's for the same service. Each side says 可以用 or what it lacks; 聽 has 試試看 (record a sentence, show what was heard), 說 has 試聽 and the voice list. speech.rs does the calls; xAI's both ways were checked for real (Mandarin read, then heard back, in Traditional characters). - The brain does it all: the phone POSTs its recording (MediaRecorder) to /api/voice/transcribe, screens to /api/sync/voice/transcribe; answers come back as MP3 from …/voice/speech and are played on the device (rodio; an <audio> on the phone, 「唸出來」 in a message's menu). Keys stay on the brain (the voice keys are redacted for screens like the others). - No service, no voice anywhere: the mic, 語音聊天, 會議錄音 and 朗讀 only appear once 聽 (and 說) can be called; the phone's state says which. Without voice the send arrow just rests where 語音聊天 was. - 會議錄音 is uploaded to the brain, which turns it into text in the background and hands it to the bot itself: a meeting is longer than the 35 s the account lets a request wait, and a brain on a server has no window (the jobs are polled in background()). - Recognisers answer Mandarin in Simplified: in a Traditional Chinese window or phone the text becomes Traditional with Taiwan wording. - Older saves: whoever had an OpenAI key keeps voice input (聽 = OpenAI); everyone else starts with it off. Bots' macOS voice names are cleared. 對話詳細資訊's 加入會議 started plain voice input; it starts a meeting now.
2026-11-10 14:58:18 +00:00
fn a_newer_say_or_stop_ends_the_playing() {
let note = std::sync::Arc::new(std::sync::Mutex::new(None));
// The service failing: said in the note, and nothing is playing after.
say(|| Err("xAI 不接受這把金鑰".into()), note.clone());
let t = Instant::now();
while speaking() && t.elapsed() < Duration::from_secs(2) {
std::thread::sleep(Duration::from_millis(10));
}
assert!(!speaking());
assert_eq!(note.lock().unwrap().as_deref(), Some("xAI 不接受這把金鑰"));
// Stopped while the sound was still on its way: it never plays, and says nothing.
let quiet = std::sync::Arc::new(std::sync::Mutex::new(None));
say(|| {
std::thread::sleep(Duration::from_millis(150));
Err("late".into())
}, quiet.clone());
assert!(speaking());
stop_speaking();
assert!(!speaking());
std::thread::sleep(Duration::from_millis(250));
assert!(!speaking() && quiet.lock().unwrap().is_none());
assert_eq!(length_words(7_200), "2 小時");
}
/// The 提示音 as a file to listen to: ANYBOT_TEST_OUT=chime.wav cargo test --bin anybot chime_to_file -- --ignored
#[test]
#[ignore]
fn chime_to_file() {
std::fs::write(std::env::var("ANYBOT_TEST_OUT").unwrap(), crate::mic::wav(&chime_samples(44_100), 44_100)).unwrap();
}
#[test]
fn the_chime_is_short_quiet_and_ends_in_silence() {
let rate = 44_100;
let s = chime_samples(rate);
let secs = s.len() as f32 / rate as f32;
assert!((0.6..=1.0).contains(&secs), "{secs} s");
let peak = s.iter().fold(0.0f32, |m, x| m.max(x.abs()));
assert!(peak > 0.1 && peak < 0.5, "peak {peak}");
// No click at the end: the last 10 ms are next to nothing.
assert!(s[s.len() - rate as usize / 100..].iter().all(|x| x.abs() < 0.005));
// Two notes: the second starts later and higher, so the start is the first note alone.
assert!(s[..rate as usize / 10].iter().any(|x| x.abs() > 0.05));
}
}