知了 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: with the microphone open, the meeting recording keeps your own voice too (#19)
wqugurua4ecf97be0c7
diff --git a/Sources/Cicada/AppModel.swift b/Sources/Cicada/AppModel.swiftindex 23e3410..0b8d7b7 100644--- a/Sources/Cicada/AppModel.swift+++ b/Sources/Cicada/AppModel.swift@@ -694,6 +694,9 @@ final class AppModel: ObservableObject {if settings.recordAudio {listen.router.setRecording(store.systemAudioURL(session.id))speak.setRecording(store.micAudioURL(session.id))+ // Here, not when the mic opens: one clock with the Mac's audio, and opening the mic+ // again mid-meeting must not start the file over.+ roomListen.router.setRecording(store.roomAudioURL(session.id))}listen.start()if listen.isRunning, settings.hearsBoth { startRoomSide() }@@ -716,6 +719,7 @@ final class AppModel: ObservableObject {stopRoomSide()listen.stop()listen.router.setRecording(nil)+ roomListen.router.setRecording(nil)speak.setRecording(nil)if let held = heldJoin {heldJoin = nildiff --git a/Sources/Cicada/AudioFiles.swift b/Sources/Cicada/AudioFiles.swiftindex f73b508..93d1639 100644--- a/Sources/Cicada/AudioFiles.swift+++ b/Sources/Cicada/AudioFiles.swift@@ -69,4 +69,64 @@ enum AudioFileWriter {try? FileManager.default.removeItem(at: url)}}++ /// Adds `other` into `url` (two recordings on one clock from their first sample) and writes+ /// the sum over `url` in its format; the longer of the two sets the length. False leaves both.+ nonisolated static func mix(_ other: URL, into url: URL) -> Bool {+ guard let a = try? AVAudioFile(forReading: url), let b = try? AVAudioFile(forReading: other) else { return false }+ let format = a.processingFormat+ let tmp = url.deletingLastPathComponent().appendingPathComponent("mixing-" + url.lastPathComponent)+ try? FileManager.default.removeItem(at: tmp)+ let chunk: AVAudioFrameCount = 16384+ guard format.commonFormat == .pcmFormatFloat32,+ let out = open(tmp, format: format),+ let bufA = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: chunk),+ let bufB = AVAudioPCMBuffer(pcmFormat: b.processingFormat, frameCapacity: chunk) else { return false }+ let converter = PCMConverter()+ var pending: [Float] = [] // `other`, in `url`'s format, not mixed yet+ var aDone = false, bDone = false+ do {+ while true {+ while !bDone, pending.count < Int(chunk) {+ do { try b.read(into: bufB, frameCount: chunk) } catch { bDone = true; break }+ if bufB.frameLength == 0 { bDone = true; break }+ if let c = converter.convert(bufB, to: format), let d = c.floatChannelData {+ pending.append(contentsOf: UnsafeBufferPointer(start: d[0], count: Int(c.frameLength)))+ }+ }+ if !aDone {+ do { try a.read(into: bufA, frameCount: chunk) } catch { bufA.frameLength = 0 }+ if bufA.frameLength == 0 { aDone = true }+ }+ if aDone {+ // `url` ended first: the rest of `other` over silence.+ let n = min(Int(chunk), pending.count)+ if n == 0 { break }+ bufA.frameLength = AVAudioFrameCount(n)+ for ch in 0..<Int(format.channelCount) { bufA.floatChannelData![ch].update(repeating: 0, count: n) }+ }+ let n = Int(bufA.frameLength), take = min(n, pending.count)+ for ch in 0..<Int(format.channelCount) {+ let d = bufA.floatChannelData![ch]+ for i in 0..<take { d[i] = max(-1, min(1, d[i] + pending[i])) }+ }+ pending.removeFirst(take)+ try out.write(from: bufA)+ }+ } catch {+ debugLog("audio mix failed \(url.lastPathComponent): \(error)")+ try? FileManager.default.removeItem(at: tmp)+ return false+ }+ // Closes the file before it takes `url`'s place.+ _ = consume out+ do {+ _ = try FileManager.default.replaceItemAt(url, withItemAt: tmp)+ return true+ } catch {+ debugLog("audio mix failed \(url.lastPathComponent): \(error)")+ try? FileManager.default.removeItem(at: tmp)+ return false+ }+ }}diff --git a/Sources/Cicada/SessionStore.swift b/Sources/Cicada/SessionStore.swiftindex 41717b5..8fe15ac 100644--- a/Sources/Cicada/SessionStore.swift+++ b/Sources/Cicada/SessionStore.swift@@ -79,7 +79,7 @@ struct Session: Codable, Identifiable, Equatable {}/// One folder per meeting under ~/Library/Application Support/LiveSubs/Sessions/<id>/:-/// session.json, system.m4a (what you heard) and mic.m4a (what you said).+/// session.json, system.m4a (what you heard, the room mic folded in) and mic.m4a (what you said).@MainActorfinal class SessionStore: ObservableObject {@Published private(set) var sessions: [Session] = []@@ -102,6 +102,10 @@ final class SessionStore: ObservableObject {func folder(_ id: String) -> URL { root.appendingPathComponent(id, isDirectory: true) }func systemAudioURL(_ id: String) -> URL { folder(id).appendingPathComponent("system.m4a") }func micAudioURL(_ id: String) -> URL { folder(id).appendingPathComponent("mic.m4a") }+ /// 电脑和会议室: the room mic, beside system.m4a on the meeting's clock until the meeting ends,+ /// then folded into it (`finishAudio`), so a record still has one recording.+ func roomAudioURL(_ id: String) -> URL { folder(id).appendingPathComponent("room.m4a") }+ private func audioURLs(_ id: String) -> [URL] { [systemAudioURL(id), micAudioURL(id), roomAudioURL(id)] }private func load() {let dirs = (try? FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)) ?? []@@ -147,7 +151,7 @@ final class SessionStore: ObservableObject {let now = Date()sessions[i].endedAt = at.map { min(now, max(sessions[i].startedAt, $0)) } ?? nowliveID = nil- sessions[i].hasAudio = [systemAudioURL(id), micAudioURL(id)].contains {+ sessions[i].hasAudio = audioURLs(id).contains {FileManager.default.fileExists(atPath: $0.path) || FileManager.default.fileExists(atPath: AudioFileWriter.partial($0).path)}if sessions[i].lines.isEmpty {@@ -158,8 +162,9 @@ final class SessionStore: ObservableObject {return}// Only the recording: it plays, and is transcribed again, like an imported file.- let system = systemAudioURL(id)- let heard = [system, AudioFileWriter.partial(system)].contains { FileManager.default.fileExists(atPath: $0.path) }+ let system = systemAudioURL(id), room = roomAudioURL(id)+ let heard = [system, AudioFileWriter.partial(system), room, AudioFileWriter.partial(room)]+ .contains { FileManager.default.fileExists(atPath: $0.path) }sessions[i].sourcePath = (heard ? system : micAudioURL(id)).path}saveNow(id)@@ -167,18 +172,32 @@ final class SessionStore: ObservableObject {}private func hasPartialAudio(_ id: String) -> Bool {- [systemAudioURL(id), micAudioURL(id)].contains { FileManager.default.fileExists(atPath: AudioFileWriter.partial($0).path) }+ audioURLs(id).contains { FileManager.default.fileExists(atPath: AudioFileWriter.partial($0).path) }}/// Turns the meeting's recordings into .m4a files (call after the recorders are closed).func finishAudio(_ id: String, until: Double? = nil) {- let urls = [systemAudioURL(id), micAudioURL(id)]+ let urls = audioURLs(id), system = systemAudioURL(id), room = roomAudioURL(id)Task.detached(priority: .utility) {for u in urls { await AudioFileWriter.finish(u, until: until) }+ Self.foldRoom(room, into: system)await self.markAudioFinished(id)}}+ /// One recording per meeting, both sides in it: the room mic goes into system.m4a (or becomes+ /// it, when the Mac played nothing). Waits while system.aac is left over from a cut rewrap:+ /// the next launch finishes it and folds again.+ nonisolated private static func foldRoom(_ room: URL, into system: URL) {+ let fm = FileManager.default+ guard fm.fileExists(atPath: room.path), !fm.fileExists(atPath: AudioFileWriter.partial(system).path) else { return }+ if !fm.fileExists(atPath: system.path) {+ try? fm.moveItem(at: room, to: system)+ } else if AudioFileWriter.mix(room, into: system) {+ try? fm.removeItem(at: room)+ }+ }+private func markAudioFinished(_ id: String) {audioFinished = id}diff --git a/Sources/Cicada/Views.swift b/Sources/Cicada/Views.swiftindex 1075be4..1823f88 100644--- a/Sources/Cicada/Views.swift+++ b/Sources/Cicada/Views.swift@@ -852,7 +852,8 @@ struct MainWindowView: View {.onChange(of: current?.id, initial: true) { _, _ in loadPlayer() }// A meeting that ends while it is shown, and its recording once it is rewrapped into an .m4a..onChange(of: store.liveID) { _, _ in loadPlayer() }- .onChange(of: store.audioFinished) { _, id in if id == current?.id { loadPlayer() } }+ // Opened afresh: a file opened before the room was mixed in (#19) would play one side only.+ .onChange(of: store.audioFinished) { _, id in if id == current?.id { player.unload(); loadPlayer() } }.onReceive(NotificationCenter.default.publisher(for: .debugPlay)) { n inif let t = n.object as? Double { player.play(from: t) }}diff --git a/Tests/CicadaTests/RoomRecordingTests.swift b/Tests/CicadaTests/RoomRecordingTests.swiftnew file mode 100644index 0000000..388681d--- /dev/null+++ b/Tests/CicadaTests/RoomRecordingTests.swift@@ -0,0 +1,78 @@+import AVFoundation+import Foundation+import Testing+@testable import Cicada++/// 电脑和会议室 records the room mic too, and the meeting keeps one recording with both (issue #19).+@MainActor @Suite struct RoomRecordingTests {+ let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 16000, channels: 1, interleaved: false)!++ func folder() -> URL {+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cicada-room-\(UUID().uuidString)")+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ return dir+ }++ /// `silent` seconds of nothing, then `seconds` of a tone.+ func write(_ url: URL, silent: Double = 0, seconds: Double, hz: Double) {+ let file = AudioFileWriter.open(url, format: format)!+ let n = Int((silent + seconds) * 16000)+ let buf = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(n))!+ buf.frameLength = AVAudioFrameCount(n)+ let start = Int(silent * 16000)+ for i in 0..<n { buf.floatChannelData![0][i] = i < start ? 0 : Float(0.2 * sin(2 * .pi * hz * Double(i) / 16000)) }+ try! file.write(from: buf)+ }++ /// RMS of each half-second of the file.+ func levels(_ url: URL) -> [Float] {+ let file = try! AVAudioFile(forReading: url)+ let buf = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length))!+ try! file.read(into: buf)+ let d = buf.floatChannelData![0], step = Int(file.processingFormat.sampleRate / 2)+ return stride(from: 0, to: Int(buf.frameLength) - step / 2, by: step).map { s in+ let e = min(s + step, Int(buf.frameLength))+ return (((s..<e).map { d[$0] * d[$0] }.reduce(0, +)) / Float(e - s)).squareRoot()+ }+ }++ @Test func theRoomIsMixedIntoTheMacsRecordingOnOneClock() {+ let dir = folder()+ let system = dir.appendingPathComponent("system.m4a"), room = dir.appendingPathComponent("room.m4a")+ write(system, seconds: 2, hz: 440)+ write(room, silent: 1, seconds: 2, hz: 660)+ #expect(AudioFileWriter.mix(room, into: system))+ let l = levels(system)+ #expect(l.count >= 6) // the longer of the two: 3 s+ #expect(l[1] > 0.1 && l[1] < 0.17) // the Mac alone+ #expect(l[3] > 0.17) // both+ #expect(l[5] > 0.1) // the room alone, after the Mac's file ended+ }++ @Test func aMeetingKeepsTheRoomInItsOneRecording() async throws {+ let root = folder()+ let store = SessionStore(root: root)+ let id = store.begin().id+ write(AudioFileWriter.partial(store.systemAudioURL(id)), seconds: 2, hz: 440)+ write(AudioFileWriter.partial(store.roomAudioURL(id)), seconds: 2, hz: 660)+ store.end(heardSpeech: true)+ for _ in 0..<100 where store.audioFinished != id { try await Task.sleep(for: .milliseconds(50)) }+ #expect(store.audioFinished == id)+ #expect(store.session(id)?.hasAudio == true)+ #expect(FileManager.default.fileExists(atPath: store.systemAudioURL(id).path))+ #expect(!FileManager.default.fileExists(atPath: store.roomAudioURL(id).path))+ #expect(levels(store.systemAudioURL(id)).dropLast().allSatisfy { $0 > 0.17 })+ }++ @Test func theRoomAloneBecomesTheRecording() async throws {+ let root = folder()+ let store = SessionStore(root: root)+ let id = store.begin().id+ write(AudioFileWriter.partial(store.roomAudioURL(id)), seconds: 2, hz: 660)+ store.end(heardSpeech: true)+ for _ in 0..<100 where store.audioFinished != id { try await Task.sleep(for: .milliseconds(50)) }+ #expect(FileManager.default.fileExists(atPath: store.systemAudioURL(id).path))+ #expect(!FileManager.default.fileExists(atPath: store.roomAudioURL(id).path))+ #expect(store.session(id)?.sourcePath == store.systemAudioURL(id).path)+ }+}diff --git a/site/changelog.json b/site/changelog.jsonindex fbb5a86..3e9c52c 100644--- a/site/changelog.json+++ b/site/changelog.json@@ -1,4 +1,21 @@[+ {+ "version": "1.6.1",+ "date": null,+ "title": "打开麦克风时,自己的声音也录下来",+ "summary": "打开麦克风后,会议录音里也有麦克风听到的声音,会后能回放自己和会议室里的人说的话。",+ "image": null,+ "items": [+ {+ "kind": "fixed",+ "platforms": [+ "mac"+ ],+ "title": "打开麦克风时,会议录音里也有自己的声音。",+ "text": "以前打开麦克风后,麦克风这一路只记文字,不存原声:会后只能回放电脑里对方的声音。现在两边录在同一个录音里,回放时都听得到。用扬声器开会时,录音里对方的声音会叠一点从麦克风收进来的回声。"+ }+ ]+ },{"version": "1.6.0","date": "2026-11-08",