知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.
Swift androidlinuxlive-captionsmacosmeeting-notesmenubar-appsimultaneous-interpretationspeech-recognitionsubtitlesswiftswiftuitranslationwindows
fix: key clicks in the meeting audio no longer count as someone speaking, so pauses and the end of a meeting are noticed on time
wquguru858e7632da33
diff --git a/Sources/Cicada/AudioRouter.swift b/Sources/Cicada/AudioRouter.swiftindex 0ec1c94..924b7ef 100644--- a/Sources/Cicada/AudioRouter.swift+++ b/Sources/Cicada/AudioRouter.swift@@ -31,11 +31,8 @@ final class AudioRouter: @unchecked Sendable {func holdAudio(_ seconds: Double) {queue.async { [self] in ringLimit = seconds }}- private var voicedTotal = 0.0- private var silenceRun = 0.0- private var sinceGap = 0.0- /// The last short pause between words, on the analyzer's clock: where it ended and how long it was.- private var pause: (end: Double, length: Double) = (0, 0)+ /// Speech, pauses and gaps; pauses are on the analyzer's clock.+ private var activity = VoiceActivity(gap: AudioRouter.gapSeconds)/// Voiceprints (说话人识别): the last `voiceLimit` seconds as 16 kHz mono floats, placed on/// the analyzer clock so a result's time range finds its audio.@@ -79,11 +76,10 @@ final class AudioRouter: @unchecked Sendable {private var recorder: AVAudioFile?/// When a block counts as speech (pauses, language detection, the silence that ends a meeting).- private var gate = VoiceGate()func setRoomGate(_ on: Bool) {- queue.async { [self] in gate = VoiceGate(adaptive: on) }+ queue.async { [self] in activity.gate = VoiceGate(adaptive: on) }}- func gateThreshold() -> Float { queue.sync { gate.threshold } }+ func gateThreshold() -> Float { queue.sync { activity.gate.threshold } }/// Loudest buffer since the last `takeLevel()`, for the level meter.private var peak: Float = 0@@ -106,16 +102,8 @@ final class AudioRouter: @unchecked Sendable {let rms = (sum / Float(n)).squareRoot()peak = max(peak, rms)let seconds = Double(n) / mono.format.sampleRate- let voiced = gate.voiced(rms)- if voiced {- if silenceRun >= 0.12, sink != nil { pause = (fed, silenceRun) }- if silenceRun >= Self.gapSeconds { sinceGap = 0 }- voicedTotal += seconds- silenceRun = 0- } else {- silenceRun += seconds- }- sinceGap += seconds+ let voiced = activity.feed(UnsafeBufferPointer(start: data[0], count: n), rate: mono.format.sampleRate,+ clock: fed, pauses: sink != nil)guard let format, let converted = converter.convert(mono, to: format) else { return }sink?.append(converted)@@ -155,14 +143,14 @@ final class AudioRouter: @unchecked Sendable {/// Analyzer clock now, the silence running at the end of it, and the last pause before that.func clock() -> (fed: Double, silence: Double, pause: (end: Double, length: Double)) {// The return type spelled out: Swift 6.4 (Xcode 27) crashes inferring this labelled tuple.- queue.sync { () -> (fed: Double, silence: Double, pause: (end: Double, length: Double)) in (fed, silenceRun, pause) }+ queue.sync { () -> (fed: Double, silence: Double, pause: (end: Double, length: Double)) in (fed, activity.silenceRun, activity.pause) }}func attach(_ stream: RecognitionStream, replaySeconds: Double = 0) {let format = stream.formatqueue.sync {fed = 0- pause = (0, 0)+ activity.clearPause()// The clock restarts; replayed audio (below) keeps its samples at the new times.let keptVoice = voicevoice = []@@ -200,9 +188,7 @@ final class AudioRouter: @unchecked Sendable {ringSeconds = 0voice = []voiceStart = 0- voicedTotal = 0- silenceRun = 0- sinceGap = 0+ activity = VoiceActivity(gate: activity.gate, gap: Self.gapSeconds)}}@@ -214,7 +200,8 @@ final class AudioRouter: @unchecked Sendable {acc += item.secondsif item.voiced { voiced += item.seconds }}- return Stats(voicedTotal: voicedTotal, silenceRun: silenceRun, sinceGap: sinceGap, recentVoiced: voiced)+ return Stats(voicedTotal: activity.voicedTotal, silenceRun: activity.silenceRun, sinceGap: activity.sinceGap,+ recentVoiced: voiced)}}diff --git a/Sources/Cicada/VoiceActivity.swift b/Sources/Cicada/VoiceActivity.swiftnew file mode 100644index 0000000..1b2ee46--- /dev/null+++ b/Sources/Cicada/VoiceActivity.swift@@ -0,0 +1,97 @@+import Foundation++/// Speech and silence over time, block by block: what `AudioRouter` knows about pauses, gaps and+/// how much was said. The loudness line is `VoiceGate`'s; on top of it a lone loud blip (a key+/// click, a cough of the speakers) is not speech until the sound has lasted `onset`, so it neither+/// ends the silence that marks a gap or the end of a meeting nor splits a pause in two. Once speech+/// is on, it stays on down to `hold` × the line, so a word's quiet ending isn't a pause.+/// `CICADA_VAD_EVAL` in `VoiceActivityTests` measures both on labelled clips (`scripts/vad-clips.py`).+struct VoiceActivity {+ struct Tuning: Equatable {+ /// Seconds of sound before it counts as speech.+ var onset: Double+ /// Speech goes on down to this fraction of the gate's line.+ var hold: Float+ static let none = Tuning(onset: 0, hold: 1)+ static let standard = Tuning(onset: 0.03, hold: 0.5)+ }++ /// A silence this long between sounds is a pause (where a long line may be cut).+ static let shortestPause = 0.12++ var gate: VoiceGate+ var tuning: Tuning+ private(set) var voicedTotal = 0.0+ private(set) var silenceRun = 0.0+ /// Seconds since the last silence of ≥ `gap` ended.+ private(set) var sinceGap = 0.0+ /// The last pause between sounds: where it ended (on the caller's clock) and how long it was.+ private(set) var pause: (end: Double, length: Double) = (0, 0)+ private var speaking = false+ /// Sound heard but not yet long enough to be speech: counted as silence until it is.+ private var pending = 0.0+ private let gap: Double++ init(gate: VoiceGate = VoiceGate(), tuning: Tuning = .standard, gap: Double) {+ self.gate = gate+ self.tuning = tuning+ self.gap = gap+ }++ /// A new analyzer's clock starts at zero: a pause on the old one means nothing there.+ mutating func clearPause() { pause = (0, 0) }++ /// A block of audio as it arrives. The Mac's own audio is judged in 10 ms steps whatever the+ /// tap's buffer size, so the onset means the same everywhere; the room mic's gate learns its+ /// noise per block (`VoiceGate.blocksPerSecond`), so it takes whole blocks. Returns whether any+ /// of it is speech.+ mutating func feed(_ samples: UnsafeBufferPointer<Float>, rate: Double, clock: Double, pauses: Bool = true) -> Bool {+ let step = gate.adaptive ? samples.count : max(1, Int(rate / 100))+ var voiced = false+ var i = 0+ while i < samples.count {+ let end = min(samples.count, i + step)+ var sum: Float = 0+ for k in i..<end { sum += samples[k] * samples[k] }+ let rms = (sum / Float(end - i)).squareRoot()+ if feed(rms: rms, seconds: Double(end - i) / rate, clock: clock + Double(i) / rate, pauses: pauses) { voiced = true }+ i = end+ }+ return voiced+ }++ /// One block of `seconds` at `rms`, starting at `clock`. Returns whether it is speech;+ /// `pauses` false keeps the last pause as it is (nothing is listening for it).+ mutating func feed(rms: Float, seconds: Double, clock: Double, pauses: Bool = true) -> Bool {+ // The room's line already sits at twice its noise: half of it is the fan, and speech would never end.+ let hold = gate.adaptive ? 1 : tuning.hold+ let line = gate.threshold+ let loud = gate.voiced(rms) || (speaking && rms >= line * hold)+ if !loud {+ speaking = false+ silenceRun += pending + seconds+ pending = 0+ sinceGap += seconds+ return false+ }+ if !speaking {+ pending += seconds+ // Not yet: the blip is part of the silence so far.+ guard pending >= tuning.onset else {+ sinceGap += seconds+ return false+ }+ // The sound that made it speech started `pending − seconds` before this block.+ let started = clock + seconds - pending+ if silenceRun >= Self.shortestPause, pauses { pause = (started, silenceRun) }+ if silenceRun >= gap { sinceGap = pending - seconds }+ voicedTotal += pending - seconds+ speaking = true+ silenceRun = 0+ pending = 0+ }+ voicedTotal += seconds+ sinceGap += seconds+ return true+ }+}diff --git a/Tests/CicadaTests/VoiceActivityTests.swift b/Tests/CicadaTests/VoiceActivityTests.swiftnew file mode 100644index 0000000..cd6e377--- /dev/null+++ b/Tests/CicadaTests/VoiceActivityTests.swift@@ -0,0 +1,213 @@+import AVFoundation+import Foundation+import Testing+@testable import Cicada++@Suite struct VoiceActivityTests {+ /// Blocks of `seconds` at `rms`, fed one after another on a running clock.+ private func run(_ a: inout VoiceActivity, _ blocks: [(rms: Float, seconds: Double)], clock: inout Double) {+ for b in blocks {+ _ = a.feed(rms: b.rms, seconds: b.seconds, clock: clock)+ clock += b.seconds+ }+ }++ private func repeated(_ rms: Float, _ seconds: Double, block: Double = 512.0 / 48000) -> [(rms: Float, seconds: Double)] {+ Array(repeating: (rms, block), count: Int((seconds / block).rounded()))+ }++ @Test func aKeyClickDoesNotEndTheSilence() {+ var a = VoiceActivity(gap: 1.5), clock = 0.0+ run(&a, repeated(0.05, 1), clock: &clock)+ run(&a, repeated(0, 1), clock: &clock)+ run(&a, [(0.05, 512.0 / 48000)], clock: &clock) // one 11 ms click+ run(&a, repeated(0, 0.8), clock: &clock)+ #expect(a.silenceRun >= 1.5)+ }++ @Test func speechAfterAPauseMarksIt() {+ var a = VoiceActivity(gap: 1.5), clock = 0.0+ run(&a, repeated(0.05, 1), clock: &clock)+ run(&a, repeated(0, 0.5), clock: &clock)+ run(&a, repeated(0.05, 0.5), clock: &clock)+ // The pause ended where the sound started, not where it was confirmed.+ #expect(abs(a.pause.end - 1.5) < 0.012)+ #expect(abs(a.pause.length - 0.5) < 0.012)+ #expect(abs(a.voicedTotal - 1.5) < 0.012)+ #expect(a.silenceRun == 0)+ }++ @Test func aGapRestartsTheCount() {+ var a = VoiceActivity(gap: 1.5), clock = 0.0+ run(&a, repeated(0.05, 3), clock: &clock)+ run(&a, repeated(0, 2), clock: &clock)+ run(&a, repeated(0.05, 1), clock: &clock)+ #expect(abs(a.sinceGap - 1) < 0.012)+ }++ @Test func aWordsQuietEndingStaysSpeech() {+ var a = VoiceActivity(gap: 1.5), clock = 0.0+ run(&a, repeated(0.05, 0.5), clock: &clock)+ run(&a, repeated(0.007, 0.2), clock: &clock) // under the line, over half of it+ #expect(a.silenceRun == 0)+ // From quiet, the same level is not speech.+ var b = VoiceActivity(gap: 1.5)+ clock = 0+ run(&b, repeated(0.007, 0.2), clock: &clock)+ #expect(b.voicedTotal == 0)+ }++ @Test func untunedIsTheBareGate() {+ var a = VoiceActivity(tuning: .none, gap: 1.5), clock = 0.0+ run(&a, repeated(0.05, 1), clock: &clock)+ run(&a, repeated(0, 1), clock: &clock)+ run(&a, [(0.05, 512.0 / 48000)], clock: &clock)+ #expect(a.silenceRun == 0)+ #expect(abs(a.pause.length - 1) < 0.012)+ }+}++/// The VAD evaluation: clips from `scripts/vad-clips.py`, with where the speech is, run through+/// `VoiceActivity` as the system tap and the room mic deliver them, for several tunings.+/// python3 scripts/vad-clips.py && CICADA_VAD_EVAL=build/vad-eval scripts/test.sh --filter VADEval+@Suite(.enabled(if: ProcessInfo.processInfo.environment["CICADA_VAD_EVAL"] != nil))+struct VADEval {+ struct Clip {+ let name: String+ let room: Bool+ let samples: [Float]+ let rate: Double+ let speech: [(Double, Double)]+ }++ struct Score {+ /// Seconds called speech with no speech near (> 50 ms from a line).+ var falseSeconds = 0.0+ /// Times speech started with no line there.+ var falseStarts = 0+ /// Gaps between lines of ≥ `gapSeconds` that never got a silence that long.+ var missedGaps = 0+ var gaps = 0+ /// Pauses of ≥ 0.3 s found inside a line (where a sentence cut lands).+ var splits = 0+ /// Seconds of a line called silence.+ var missedSeconds = 0.0+ var speechSeconds = 0.0+ /// Mean delay from a line's start to the first block called speech.+ var lag = 0.0+ }++ static func load() throws -> [Clip] {+ let dir = URL(fileURLWithPath: ProcessInfo.processInfo.environment["CICADA_VAD_EVAL"]!)+ let names = try FileManager.default.contentsOfDirectory(atPath: dir.path).filter { $0.hasSuffix(".wav") }.sorted()+ return try names.map { name in+ let file = try AVAudioFile(forReading: dir.appendingPathComponent(name))+ let buf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length))!+ try file.read(into: buf)+ let samples = Array(UnsafeBufferPointer(start: buf.floatChannelData![0], count: Int(buf.frameLength)))+ let json = try JSONSerialization.jsonObject(with: Data(contentsOf: dir.appendingPathComponent(+ name.replacingOccurrences(of: ".wav", with: ".json")))) as! [String: Any]+ let speech = (json["speech"] as! [[Double]]).map { ($0[0], $0[1]) }+ return Clip(name: String(name.dropLast(4)), room: json["source"] as? String == "room",+ samples: samples, rate: file.processingFormat.sampleRate, speech: speech)+ }+ }++ /// `block`: frames per buffer, as the source delivers them (the mic tap's 4096; the system tap's+ /// is the HAL buffer size, so several are tried).+ static func score(_ clip: Clip, _ tuning: VoiceActivity.Tuning, block: Int) -> Score {+ var a = VoiceActivity(gate: VoiceGate(adaptive: clip.room), tuning: tuning, gap: AudioRouter.gapSeconds)+ var s = Score()+ var wasVoiced = false+ var started = Set<Int>()+ var lags: [Double] = []+ var longestSilence: [Int: Double] = [:] // gap index → longest silence run seen in it+ var lastPause = (end: 0.0, length: 0.0)+ func line(at t: Double, margin: Double = 0) -> Int? {+ clip.speech.firstIndex { t >= $0.0 - margin && t < $0.1 + margin }+ }+ var i = 0+ while i + block <= clip.samples.count {+ let t = Double(i) / clip.rate, dt = Double(block) / clip.rate+ let voiced = clip.samples.withUnsafeBufferPointer {+ a.feed(UnsafeBufferPointer(rebasing: $0[i..<(i + block)]), rate: clip.rate, clock: t)+ }+ let mid = t + dt / 2+ if voiced {+ if line(at: mid, margin: 0.05) == nil {+ s.falseSeconds += dt+ if !wasVoiced { s.falseStarts += 1 }+ }+ if let l = line(at: mid), !started.contains(l) {+ started.insert(l)+ lags.append(max(0, t - clip.speech[l].0))+ }+ } else if line(at: mid) != nil {+ s.missedSeconds += dt+ }+ if line(at: mid) != nil { s.speechSeconds += dt }+ // Which gap this block is in: after line g, before line g + 1.+ if let g = clip.speech.indices.last(where: { clip.speech[$0].1 <= t }), g + 1 < clip.speech.count,+ t < clip.speech[g + 1].0 {+ longestSilence[g] = max(longestSilence[g] ?? 0, a.silenceRun)+ }+ if a.pause != lastPause {+ lastPause = a.pause+ let mid = a.pause.end - a.pause.length / 2+ if a.pause.length >= 0.3, line(at: mid) != nil { s.splits += 1 }+ }+ wasVoiced = voiced+ i += block+ }+ for g in 0..<(clip.speech.count - 1) where clip.speech[g + 1].0 - clip.speech[g].1 >= AudioRouter.gapSeconds + 0.2 {+ s.gaps += 1+ if (longestSilence[g] ?? 0) < AudioRouter.gapSeconds { s.missedGaps += 1 }+ }+ s.lag = lags.isEmpty ? 0 : lags.reduce(0, +) / Double(lags.count)+ return s+ }++ @Test func report() throws {+ let clips = try Self.load()+ try #require(!clips.isEmpty)+ let tunings: [(String, VoiceActivity.Tuning)] = [+ ("bare", .none),+ ("on20", .init(onset: 0.02, hold: 1)),+ ("on30", .init(onset: 0.03, hold: 1)),+ ("on50", .init(onset: 0.05, hold: 1)),+ ("on80", .init(onset: 0.08, hold: 1)),+ ("hold.5", .init(onset: 0, hold: 0.5)),+ ("std", .standard),+ ("on50h.5", .init(onset: 0.05, hold: 0.5)),+ ]+ var out = "clip tuning falseS falseN gapMiss splits missS/speechS lag\n"+ var totals: [String: Score] = [:]+ for clip in clips {+ for block in clip.room ? [4096] : [512, 1024, 2048] {+ for (tname, t) in tunings {+ let name = clip.room ? tname : "\(tname)/\(block)"+ let s = Self.score(clip, t, block: block)+ out += String(format: "%-20@ %-13@ %6.2f %6d %3d/%-3d %6d %5.2f/%-6.2f %5.3f\n",+ clip.name as NSString, name as NSString, s.falseSeconds, s.falseStarts,+ s.missedGaps, s.gaps, s.splits, s.missedSeconds, s.speechSeconds, s.lag)+ var tot = totals[name] ?? Score()+ tot.falseSeconds += s.falseSeconds; tot.falseStarts += s.falseStarts+ tot.missedGaps += s.missedGaps; tot.gaps += s.gaps; tot.splits += s.splits+ tot.missedSeconds += s.missedSeconds; tot.speechSeconds += s.speechSeconds+ tot.lag += s.lag / Double(clips.count)+ totals[name] = tot+ }+ }+ }+ out += "\nTOTAL\n"+ for name in totals.keys.sorted() {+ let s = totals[name]!+ out += String(format: "%-13@ falseS %6.2f falseN %4d gapMiss %2d/%-2d splits %3d missS %5.2f/%-6.2f lag %.3f\n",+ name as NSString, s.falseSeconds, s.falseStarts, s.missedGaps, s.gaps, s.splits,+ s.missedSeconds, s.speechSeconds, s.lag)+ }+ print(out)+ let path = ProcessInfo.processInfo.environment["CICADA_VAD_EVAL"]! + "/report.txt"+ try out.write(toFile: path, atomically: true, encoding: .utf8)+ }+}diff --git a/scripts/vad-clips.py b/scripts/vad-clips.pynew file mode 100644index 0000000..70f7284--- /dev/null+++ b/scripts/vad-clips.py@@ -0,0 +1,190 @@+#!/usr/bin/env python3+"""Makes the VAD evaluation set: labelled clips of speech with the sounds that fool a loudness gate+between the lines (typing, a notification, hold music, a fan), as the system tap and the room mic+hear them. Speech is `say`, so where each line starts and ends is known to the sample.++ python3 scripts/vad-clips.py [out_dir] # default build/vad-eval+ scripts/test.sh --filter VADEval # runs the evaluation on them (CICADA_VAD_EVAL)++Each clip is 48 kHz mono 16-bit WAV with `<name>.json`: {"source": "system"|"room", "speech": [[s, e], …]}.+Stdlib only; the seed is fixed, so the set is the same on every Mac with the same voices.+"""+import json+import math+import os+import random+import subprocess+import sys+import tempfile+import wave++RATE = 48000+OUT = sys.argv[1] if len(sys.argv) > 1 else "build/vad-eval"++LINES = {+ "Samantha": [+ "Let's start with the quarterly numbers.",+ "Revenue grew by twelve percent, mostly from the new region.",+ "Can everyone hear me okay?",+ "We should ship the update before the end of the month, but only if testing is done.",+ "Thanks, that's all from me.",+ ],+ "Tingting": [+ "我们先看一下这个季度的数据。",+ "收入增长了百分之十二,主要来自新的市场。",+ "大家能听到我说话吗?",+ "如果测试完成了,我们月底之前发布更新。",+ "好的,我这边就这些。",+ ],+}+++RINGTONES = "/System/Library/PrivateFrameworks/ToneLibrary.framework/Versions/A/Resources/Ringtones"+ALERTS = "/System/Library/Sounds"+++def read(path):+ """Any audio file macOS can decode, as 48 kHz mono floats."""+ with tempfile.TemporaryDirectory() as d:+ wav = os.path.join(d, "a.wav")+ subprocess.run(["afconvert", "-f", "WAVE", "-d", f"LEI16@{RATE}", "-c", "1", path, wav], check=True)+ with wave.open(wav) as w:+ raw = w.readframes(w.getnframes())+ return [int.from_bytes(raw[i:i + 2], "little", signed=True) / 32768 for i in range(0, len(raw), 2)]+++def say(voice, text):+ with tempfile.TemporaryDirectory() as d:+ aiff = os.path.join(d, "a.aiff")+ subprocess.run(["say", "-v", voice, "-o", aiff, text], check=True)+ x = read(aiff)+ # `say` pads with silence: the line is where the sound is.+ loud = [i for i, v in enumerate(x) if abs(v) > 0.003]+ return x[loud[0]:loud[-1] + 1]+++def scaled(x, rms_db):+ rms = math.sqrt(sum(v * v for v in x) / len(x)) or 1+ k = 10 ** (rms_db / 20) / rms+ return [v * k for v in x]+++def silence(seconds):+ return [0.0] * int(seconds * RATE)+++def typing(seconds, rng, level=0.25):+ """Key clicks: 3–8 a second, each a few ms of decaying noise, peaks around -12 dBFS."""+ x = silence(seconds)+ t = rng.uniform(0.05, 0.2)+ while t < seconds - 0.02:+ i, amp = int(t * RATE), level * rng.uniform(0.5, 1)+ for k in range(int(0.006 * RATE)):+ x[i + k] += amp * math.exp(-k / (0.0015 * RATE)) * rng.uniform(-1, 1)+ t += rng.uniform(0.12, 0.33)+ return x+++def ding(seconds):+ """A notification: two 150 ms tones, then nothing."""+ x = silence(seconds)+ for start, f in ((0.1, 880), (0.3, 1320)):+ i = int(start * RATE)+ if start + 0.2 > seconds:+ break+ for k in range(int(0.15 * RATE)):+ x[i + k] = 0.2 * math.sin(2 * math.pi * f * k / RATE) * math.exp(-k / (0.08 * RATE))+ return x+++def music(seconds):+ """Hold music: a chord progression with harmonics, about -26 dBFS RMS."""+ x = silence(seconds)+ chords = [(261.6, 329.6, 392.0), (220.0, 261.6, 329.6), (174.6, 220.0, 261.6), (196.0, 246.9, 293.7)]+ beat = int(0.5 * RATE)+ for i in range(len(x)):+ c = chords[(i // beat) % len(chords)]+ env = 0.6 + 0.4 * math.exp(-(i % beat) / (0.15 * RATE))+ x[i] = env * sum(0.03 * math.sin(2 * math.pi * f * h * i / RATE) / h for f in c for h in (1, 2, 3))+ return x+++def looped(sound, seconds, rms_db):+ """`sound` repeated to fill `seconds`, at `rms_db`: a ringtone as hold music."""+ n = int(seconds * RATE)+ base = scaled(sound, rms_db)+ return [base[i % len(base)] for i in range(n)]+++def alert(sounds):+ """A system alert at the start of the gap, then nothing."""+ def fill(seconds, rng):+ x = silence(seconds)+ a = scaled(rng.choice(sounds), -22)[:len(x) - int(0.1 * RATE)]+ x[int(0.05 * RATE):int(0.05 * RATE) + len(a)] = a+ return x+ return fill+++def fan(n, rng, rms_db):+ """Room noise: low-passed white noise (a fan, an air conditioner)."""+ y, out = 0.0, []+ for _ in range(n):+ y = 0.97 * y + 0.03 * rng.uniform(-1, 1)+ out.append(y)+ return scaled(out, rms_db)+++def build(name, source, voice, gaps, speech_db, filler=None, noise_db=None, bed=None, seed=1, lines=5):+ """Lines of `voice` at `speech_db` RMS with `gaps` seconds between them, each gap filled by+ `filler(seconds, rng)` (or silence), the whole over a fan at `noise_db` or over `bed(seconds)`+ (music under the talk) when given."""+ rng = random.Random(seed)+ lines = [scaled(l, speech_db) for l in SPEECH[voice][:lines]]+ x, speech = silence(1.0), []+ for i, line in enumerate(lines):+ speech.append([len(x) / RATE, (len(x) + len(line)) / RATE])+ x += line+ g = gaps[i % len(gaps)]+ x += filler(g, rng) if filler else silence(g)+ if noise_db is not None:+ x = [a + b for a, b in zip(x, fan(len(x), rng, noise_db))]+ if bed is not None:+ x = [a + b for a, b in zip(x, bed(len(x) / RATE))]+ with wave.open(os.path.join(OUT, name + ".wav"), "wb") as w:+ w.setnchannels(1)+ w.setsampwidth(2)+ w.setframerate(RATE)+ w.writeframes(b"".join(int(max(-1, min(1, v)) * 32767).to_bytes(2, "little", signed=True) for v in x))+ with open(os.path.join(OUT, name + ".json"), "w") as f:+ json.dump({"source": source, "speech": [[round(s, 3), round(e, 3)] for s, e in speech]}, f)+ print(f"{name}: {len(x) / RATE:.1f} s, {len(speech)} lines")+++os.makedirs(OUT, exist_ok=True)+SPEECH = {v: [say(v, t) for t in lines] for v, lines in LINES.items()}+GAPS = [0.4, 2.2, 0.8, 3.0, 1.6]+# Real hold music and alerts from the system, when this macOS has them.+tones = [read(os.path.join(RINGTONES, f)) for f in ("Marimba.m4r", "Blues.m4r", "Old Phone.m4r")+ if os.path.exists(os.path.join(RINGTONES, f))]+alerts = [read(os.path.join(ALERTS, f)) for f in ("Glass.aiff", "Ping.aiff", "Submarine.aiff", "Hero.aiff")+ if os.path.exists(os.path.join(ALERTS, f))]+for v, tag in (("Samantha", "en"), ("Tingting", "zh")):+ if tones:+ build(f"system-ringtone-{tag}", "system", v, GAPS, -20,+ filler=lambda s, r: looped(r.choice(tones), s, -24))+ # Someone talking over music: every word of it must get through.+ build(f"system-overmusic-{tag}", "system", v, GAPS, -20, bed=lambda s: looped(tones[1 % len(tones)], s, -32))+ # On hold: half a minute of music between two lines, nobody talking.+ build(f"system-hold-{tag}", "system", v, [30.0], -20, filler=lambda s, r: looped(tones[0], s, -24), lines=2)+ if alerts:+ build(f"system-alert-{tag}", "system", v, GAPS, -20, filler=alert(alerts))+ # The Mac's own audio: digital silence between lines, unless something else plays.+ build(f"system-clean-{tag}", "system", v, GAPS, -20)+ build(f"system-typing-{tag}", "system", v, GAPS, -20, filler=typing)+ build(f"system-ding-{tag}", "system", v, GAPS, -20, filler=lambda s, r: ding(s))+ build(f"system-music-{tag}", "system", v, GAPS, -20, filler=lambda s, r: music(s))+ # The room: a fan under everything, a near and a far voice, someone typing.+ build(f"room-near-{tag}", "room", v, GAPS, -24, noise_db=-50)+ build(f"room-far-{tag}", "room", v, GAPS, -40, noise_db=-52)+ build(f"room-typing-{tag}", "room", v, GAPS, -28, filler=lambda s, r: typing(s, r, 0.08), noise_db=-50)diff --git a/site/changelog.json b/site/changelog.jsonindex 2ffd427..0c744e7 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -131,6 +131,14 @@],"title": "Mac 上点开始听,实时纪要窗口马上出现。","text": "不用等有人开口才知道已经在听;开机或会议软件来电时自动开始,仍等第一句话再出现。"+ },+ {+ "kind": "fixed",+ "platforms": [+ "mac"+ ],+ "title": "会议里有人敲键盘,不再被当成有人在说话。",+ "text": "一下下的按键声会打断静音,知了等不到停顿:换语言的判断和会议结束的提示都会推迟。"}]},