Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(ios): pick the voice Face to Face reads in for each language, or record your own for the other person to hear

wquguruc85d0a9ce577
diff --git a/Sources/Cicada/Voices.swift b/Sources/Cicada/Voices.swift
index f9aac7e..8988d34 100644
--- a/Sources/Cicada/Voices.swift
+++ b/Sources/Cicada/Voices.swift
@@ -161,9 +161,7 @@ enum VoiceReference {
try fm.setAttributes([.posixPermissions: 0o700], ofItemAtPath: folder.path)
if fm.fileExists(atPath: audioURL.path) { try fm.removeItem(at: audioURL) }
try fm.copyItem(at: wav, to: audioURL)
- #if !CICADA_IOS
trim(audioURL)
- #endif
try Data(text.utf8).write(to: textURL)
for url in [audioURL, textURL] {
try? fm.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)
@@ -181,7 +179,8 @@ enum VoiceReference {
// MARK: Pace
#if !CICADA_IOS
- // Mac app only, with the voice recorder below: it scores with the speak test's tokens (SpeakTest.swift).
+ // Pace is Mac app only, with the voice recorder below: it scores with the speak test's tokens
+ // (SpeakTest.swift). Trimming is shared: the iOS recorder trims what it saves too.
/// Ming copies the recording's pace into every sentence: a recital at 1.7 characters a second
/// made each sentence about 4× as long as the built-in voice says it. Below these (characters
@@ -209,6 +208,8 @@ enum VoiceReference {
return Double(w.last - w.first + 1) * Double(w.size) / sampleRate
}
+ #endif
+
/// The samples from 0.2 s before the reading to 0.2 s after it. Ming copies the clip's ending:
/// a second of silence after the last word (the pause before 读完了) made every cloned
/// sentence come back as 0.4 s of nothing (measured against Ling, 2026-11).
@@ -249,6 +250,7 @@ enum VoiceReference {
}
}
+ #if !CICADA_IOS
/// The saved recording, trimmed once: recordings made before trimming existed end in the pause.
private static var checkedTrim: Date?
static func trimSaved() {
@@ -258,6 +260,8 @@ enum VoiceReference {
checkedTrim = (try? audioURL.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate
}
+ #endif
+
private static func speechWindows(_ samples: [Float], sampleRate: Double) -> (first: Int, last: Int, size: Int)? {
let size = max(1, Int(sampleRate * 0.02))
var levels: [Float] = []
@@ -276,6 +280,7 @@ enum VoiceReference {
return (first, last, size)
}
+ #if !CICADA_IOS
/// The pace of a WAV and what it says.
static func pace(of url: URL, text: String) -> Double? {
guard let f = try? AVAudioFile(forReading: url),
diff --git a/ios/Sources/Cicada/CicadaApp.swift b/ios/Sources/Cicada/CicadaApp.swift
index 9bbafca..8bf6fa9 100644
--- a/ios/Sources/Cicada/CicadaApp.swift
+++ b/ios/Sources/Cicada/CicadaApp.swift
@@ -131,6 +131,8 @@ final class AppModel: ObservableObject {
/// 面对面同声传译 (FaceView), over everything while it is open.
lazy var face = FaceToFace(store: store, translator: translator, ling: ling)
@Published var showFace = false
+ /// 设置 › 念给对方的声音, pushed (a debug command opens it).
+ @Published var showVoices = false
/// 设置 › 快速开始, pushed (a debug command opens it).
@Published var showQuickStart = false
/// The meeting whose 导出 sheet is open.
diff --git a/ios/Sources/Cicada/FaceToFace.swift b/ios/Sources/Cicada/FaceToFace.swift
index 6ad5aa5..e0cc5ac 100644
--- a/ios/Sources/Cicada/FaceToFace.swift
+++ b/ios/Sources/Cicada/FaceToFace.swift
@@ -227,7 +227,7 @@ final class FaceToFace: ObservableObject {
record(t, from: from, to: to)
phase = .speaking(side)
contentLog("FACE [\(from.code)→\(to.code)] \(text) => \(out)")
- await voice.speak(out, language: to.code, ling: ling.hasKey ? ling : nil)
+ await voice.speak(out, language: to.code, ling: ling.hasKey ? ling : nil, mine: side == .them)
if phase == .speaking(side) { phase = .idle }
}
@@ -242,7 +242,7 @@ final class FaceToFace: ObservableObject {
record(t, from: from, to: to)
phase = .speaking(side)
turnTask = Task {
- await voice.speak(translation, language: to.code, ling: ling.hasKey ? ling : nil)
+ await voice.speak(translation, language: to.code, ling: ling.hasKey ? ling : nil, mine: side == .them)
if phase == .speaking(side) { phase = .idle }
}
}
@@ -336,20 +336,24 @@ final class FaceVoice: NSObject, AVSpeechSynthesizerDelegate {
synth.delegate = self
}
- func speak(_ text: String, language: String, ling: LingClient?) async {
+ /// `voiceID`: a voice to try (设置 › 念给对方的声音); else the one chosen for the language.
+ /// `mine`: read to me (their words), never in my own cloned voice.
+ func speak(_ text: String, language: String, ling: LingClient?, voiceID: String? = nil, mine: Bool = false) async {
// One voice at a time: a turn still being read out ends here.
stop()
try? FaceAudio.activate()
- if let ling, let voice = VoiceCatalog.ming(for: language).first, case .ming(let id) = voice.kind {
- let stream = ling.speech(text, voice: id, language: VoiceCatalog.mingLanguage(for: language))
+ let id = voiceID ?? SpeakVoices.chosenID(for: language, hasKey: ling != nil, mine: mine)
+ if let ling, let stream = Self.stream(text, id: id, language: language, ling: ling) {
let task = Task { await self.play(stream) }
streaming = task
- if await task.value { debugLog("face: spoke with Ming \(id)"); return }
+ if await task.value { debugLog("face: spoke with \(id ?? "-")"); return }
if Task.isCancelled || streaming == nil { return }
- debugLog("face: Ming sent nothing, the phone's voice instead")
+ // Ling 不可用时自动换成手机的声音.
+ debugLog("face: Ling sent nothing, the phone's voice instead")
}
let u = AVSpeechUtterance(string: text)
- u.voice = AVSpeechSynthesisVoice(language: Locale(identifier: language).language.minimalIdentifier)
+ let picked = id.flatMap { $0.hasPrefix("system:") ? AVSpeechSynthesisVoice(identifier: String($0.dropFirst(7))) : nil }
+ u.voice = picked ?? AVSpeechSynthesisVoice(language: Locale(identifier: language).language.minimalIdentifier)
?? AVSpeechSynthesisVoice(language: language)
await withCheckedContinuation { c in
spoken = c
@@ -358,6 +362,17 @@ final class FaceVoice: NSObject, AVSpeechSynthesizerDelegate {
debugLog("face: spoke with the phone's voice")
}
+ /// Ming's voice, or the user's own cloned from their recording; nil for the phone's.
+ private static func stream(_ text: String, id: String?, language: String, ling: LingClient) -> AsyncThrowingStream<Data, Error>? {
+ let lang = VoiceCatalog.mingLanguage(for: language)
+ if id == VoiceCatalog.cloneOption.id {
+ guard let ref = VoiceReference.reference() else { return nil }
+ return ling.speech(text, voice: nil, reference: ref, language: lang)
+ }
+ guard let id, id.hasPrefix("ming:") else { return nil }
+ return ling.speech(text, voice: String(id.dropFirst(5)), language: lang)
+ }
+
/// Plays the chunks as they come; false when none came.
private func play(_ stream: AsyncThrowingStream<Data, Error>) async -> Bool {
var carry = Data(), frames = 0
diff --git a/ios/Sources/Cicada/SettingsView.swift b/ios/Sources/Cicada/SettingsView.swift
index 0bdb3dd..aef9efa 100644
--- a/ios/Sources/Cicada/SettingsView.swift
+++ b/ios/Sources/Cicada/SettingsView.swift
@@ -91,9 +91,13 @@ struct SettingsView: View {
.tint(Ink.secondary)
}
Hairline()
- row(Text("念给对方的声音")) {
- Text(verbatim: ling.hasKey ? "Ming" : L("手机自带")).foregroundStyle(Ink.secondary)
+ NavigationLink { VoicesPage(face: model.face) } label: {
+ row(Text("念给对方的声音")) {
+ Text(verbatim: voiceSummary).foregroundStyle(Ink.secondary).lineLimit(1)
+ Chevron()
+ }
}
+ .buttonStyle(RowPress())
}
SectionLabel(text: L("快速开始"))
Card {
@@ -116,6 +120,7 @@ struct SettingsView: View {
.background(Ink.ground)
.navigationDestination(isPresented: $model.showWordList) { WordListPage(vocabulary: model.vocabulary) }
.navigationDestination(isPresented: $model.showQuickStart) { QuickStartPage() }
+ .navigationDestination(isPresented: $model.showVoices) { VoicesPage(face: model.face) }
.toolbar(sheet ? .visible : .hidden, for: .navigationBar)
.navigationTitle(sheet ? Text("设置") : Text(""))
.navigationBarTitleDisplayMode(.inline)
@@ -129,6 +134,24 @@ struct SettingsView: View {
.tint(Ink.ink)
}
+ /// A row with its one grey helper line under it.
+ private func helped<R: View>(_ row: R, _ help: String) -> some View {
+ VStack(alignment: .leading, spacing: 0) {
+ row
+ Text(verbatim: help).font(.footnote).foregroundStyle(Ink.secondary)
+ .padding(.horizontal, 16).padding(.top, -6).padding(.bottom, 10)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+
+ /// 念给对方的声音 at a glance: the voice the other person hears.
+ private var voiceSummary: String {
+ let lang = model.face.theirs.code
+ let id = SpeakVoices.chosenID(for: lang, hasKey: ling.hasKey)
+ if id == VoiceCatalog.cloneOption.id { return L("我自己的声音") }
+ return VoiceCatalog.options(for: lang).first { $0.id == id }?.name ?? L("手机自带")
+ }
+
private func row<V: View>(_ title: Text, @ViewBuilder value: () -> V) -> some View {
HStack(spacing: 8) {
title.foregroundStyle(Ink.ink)
diff --git a/ios/Sources/Cicada/VoicesPage.swift b/ios/Sources/Cicada/VoicesPage.swift
new file mode 100644
index 0000000..dce1045
--- /dev/null
+++ b/ios/Sources/Cicada/VoicesPage.swift
@@ -0,0 +1,386 @@
+import AVFoundation
+import SwiftUI
+
+/// 每种语言各记一个声音: the Mac's `speakVoices` (language key → voice id), read by 面对面.
+enum SpeakVoices {
+ static let key = "speakVoices"
+
+ static var all: [String: String] { UserDefaults.standard.dictionary(forKey: key) as? [String: String] ?? [:] }
+
+ /// The voice for a language: the one picked, while it can still be used (Ming and the clone need
+ /// the key, the clone its recording), else the catalog's default. `mine`: read for me (their
+ /// words in my language), where my own voice would make no sense.
+ static func chosenID(for language: String, hasKey: Bool, mine: Bool = false) -> String? {
+ if let id = all[VoiceCatalog.key(for: language)] {
+ let clone = id == VoiceCatalog.cloneOption.id
+ if id.hasPrefix("system:") { return id }
+ if hasKey, !clone || (!mine && VoiceReference.exists) { return id }
+ }
+ return VoiceCatalog.defaultID(for: language, hasKey: hasKey)
+ }
+
+ static func set(_ id: String, for language: String) {
+ var d = all
+ d[VoiceCatalog.key(for: language)] = id
+ UserDefaults.standard.set(d, forKey: key)
+ }
+}
+
+/// 设置 › 念给对方的声音: 用你自己的声音 (a recording Ming clones), then each language 面对面
+/// speaks, with Ming's voices and the phone's; ▶ tries one with a line in that language.
+struct VoicesPage: View {
+ @EnvironmentObject var model: AppModel
+ @EnvironmentObject var ling: LingClient
+ @ObservedObject var face: FaceToFace
+ @State private var chosen = SpeakVoices.all
+ @State private var trying: String?
+ @State private var recording = false
+ @State private var hasOwn = VoiceReference.exists
+ private let voice = FaceVoice()
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 0) {
+ own
+ Text("每种语言各记一个声音").font(.footnote.weight(.semibold)).foregroundStyle(Ink.secondary)
+ .padding(.horizontal, 4).padding(.top, 24)
+ ForEach(languages, id: \.self) { lang in
+ section(lang)
+ }
+ Text(ling.hasKey ? L("Ling 不可用时自动换成手机的声音") : L("填入 Ling key 后可用 Ming 声音和你自己的声音"))
+ .font(.footnote).foregroundStyle(Ink.secondary).padding(.horizontal, 4).padding(.top, 10)
+ }
+ .padding(.horizontal, 16).padding(.top, 8).padding(.bottom, 120)
+ .frame(maxWidth: 640).frame(maxWidth: .infinity)
+ }
+ .background(Ink.ground)
+ .navigationTitle(Text("念给对方的声音"))
+ .navigationBarTitleDisplayMode(.inline)
+ .sheet(isPresented: $recording, onDismiss: { hasOwn = VoiceReference.exists }) {
+ OwnVoiceSheet(locale: face.mine.locale) { recording = false }
+ }
+ .onDisappear { voice.stop() }
+ }
+
+ /// Theirs first: what 面对面 reads to the other person; then mine, what it reads to me.
+ private var languages: [String] {
+ let both = [face.theirs.code, face.mine.code]
+ return both.enumerated().filter { i, c in both.prefix(i).allSatisfy { VoiceCatalog.key(for: $0) != VoiceCatalog.key(for: c) } }.map(\.1)
+ }
+
+ private var own: some View {
+ Card {
+ VStack(alignment: .leading, spacing: 12) {
+ HStack(spacing: 12) {
+ Image(systemName: "mic.fill").font(.system(size: 18, weight: .semibold)).foregroundStyle(Ink.accentText)
+ .frame(width: 44, height: 44).background(Ink.accentWash, in: Circle())
+ VStack(alignment: .leading, spacing: 2) {
+ Text("用你自己的声音").font(.headline).foregroundStyle(Ink.ink)
+ Text("录 15 秒原声,对方听到你的音色,晚约 3 秒").font(.footnote).foregroundStyle(Ink.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ }
+ if !ling.hasKey {
+ Text("只有 Ling 能用你自己的声音").font(.footnote).foregroundStyle(Ink.secondary)
+ } else if hasOwn {
+ HStack(spacing: 10) {
+ Button { tryVoice(VoiceCatalog.cloneOption.id, face.theirs.code) } label: {
+ Label(L("试听"), systemImage: trying == VoiceCatalog.cloneOption.id ? "stop.fill" : "play.fill")
+ .font(.subheadline.weight(.semibold)).frame(maxWidth: .infinity).frame(height: 44)
+ .background(Ink.ground, in: Capsule())
+ }
+ Button { recording = true } label: {
+ Text("重录").font(.subheadline.weight(.semibold)).frame(maxWidth: .infinity).frame(height: 44)
+ .background(Ink.ground, in: Capsule())
+ }
+ Button(role: .destructive) { VoiceReference.remove(); hasOwn = false } label: {
+ Text("删除").font(.subheadline.weight(.semibold)).frame(maxWidth: .infinity).frame(height: 44)
+ .background(Ink.ground, in: Capsule())
+ }
+ }
+ .buttonStyle(.plain).foregroundStyle(Ink.ink)
+ } else {
+ Button { recording = true } label: {
+ Text("录制你的声音").font(.headline).foregroundStyle(.white)
+ .frame(maxWidth: .infinity).frame(height: 46).background(Ink.ink, in: Capsule())
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ .padding(16)
+ }
+ }
+
+ private func section(_ lang: String) -> some View {
+ let options = VoiceCatalog.options(for: lang)
+ let mine = VoiceCatalog.key(for: lang) == VoiceCatalog.key(for: face.mine.code) && lang != face.theirs.code
+ // My own voice only for what is read to the other person (这是我自己的声音。只在我说话时用它替我翻译。).
+ let rows = (!mine && hasOwn && ling.hasKey ? [VoiceCatalog.cloneOption] : []) + options
+ let current = SpeakVoices.chosenID(for: lang, hasKey: ling.hasKey, mine: mine)
+ return VStack(alignment: .leading, spacing: 6) {
+ Text(verbatim: name(lang) + " · " + (mine ? L("对方说\(Pref.name(of: face.theirs))时用") : L("对方会听到这个")))
+ .font(.footnote).foregroundStyle(Ink.secondary).padding(.horizontal, 4).padding(.top, 14)
+ Card {
+ VStack(spacing: 0) {
+ ForEach(Array(rows.enumerated()), id: \.element.id) { i, o in
+ if i > 0 { Hairline() }
+ row(o, lang: lang, on: o.id == current)
+ }
+ }
+ }
+ }
+ }
+
+ private func name(_ code: String) -> String {
+ targetLanguages.first { $0.code == code }?.name ?? sourceLanguages.first { $0.code == code }.map { Pref.name(of: $0) } ?? code
+ }
+
+ private func row(_ o: VoiceOption, lang: String, on: Bool) -> some View {
+ let usable = !o.needsKey || ling.hasKey
+ return HStack(spacing: 12) {
+ Button {
+ guard usable else { return }
+ SpeakVoices.set(o.id, for: lang)
+ chosen = SpeakVoices.all
+ } label: {
+ HStack(spacing: 10) {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(verbatim: o.name).font(.body).foregroundStyle(usable ? Ink.ink : Ink.tertiary)
+ let tags = o.kind == .clone ? [L("最像你")] : o.tags
+ if !tags.isEmpty {
+ Text(verbatim: tags.joined(separator: " · ")).font(.caption).foregroundStyle(Ink.secondary)
+ }
+ }
+ Spacer(minLength: 8)
+ if on { Image(systemName: "checkmark").font(.body.weight(.semibold)).foregroundStyle(Ink.accentText) }
+ }
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(on ? .isSelected : [])
+ Button { tryVoice(o.id, lang) } label: {
+ Image(systemName: trying == o.id ? "stop.fill" : "play.fill").font(.system(size: 12, weight: .semibold))
+ .foregroundStyle(Ink.ink).frame(width: 36, height: 36).background(Ink.ground, in: Circle())
+ }
+ .buttonStyle(.plain)
+ .frame(width: 44, height: 44)
+ .disabled(!usable)
+ .accessibilityLabel(Text("试听"))
+ }
+ .padding(.horizontal, 16).frame(minHeight: 56)
+ }
+
+ private func tryVoice(_ id: String, _ lang: String) {
+ if trying == id { voice.stop(); trying = nil; return }
+ trying = id
+ Task {
+ await voice.speak(VoiceCatalog.sample(for: lang), language: lang, ling: ling.hasKey ? ling : nil, voiceID: id)
+ if trying == id { trying = nil }
+ }
+ }
+}
+
+/// 录制你的声音: the passage to read, a meter and the seconds, 读完了; then 录好了,先听听像不像.
+struct OwnVoiceSheet: View {
+ @EnvironmentObject var ling: LingClient
+ let locale: String
+ let done: () -> Void
+ @StateObject private var rec = OwnVoiceRecorder()
+ @State private var trying = false
+ private let voice = FaceVoice()
+
+ var body: some View {
+ NavigationStack {
+ VStack(alignment: .leading, spacing: 18) {
+ Text("请用平时开会的自然语气朗读以下段落,约 15 秒,在安静环境下录制效果最佳。")
+ .font(.subheadline).foregroundStyle(Ink.secondary).fixedSize(horizontal: false, vertical: true)
+ Text(verbatim: VoiceReference.passage(for: locale))
+ .font(.title3).foregroundStyle(Ink.ink).lineSpacing(6)
+ .padding(18).frame(maxWidth: .infinity, alignment: .leading)
+ .background(Color.white, in: RoundedRectangle(cornerRadius: 20, style: .continuous))
+ Spacer(minLength: 0)
+ switch rec.phase {
+ case .idle, .failed:
+ if case .failed(let why) = rec.phase {
+ Text(verbatim: why).font(.footnote).foregroundStyle(Ink.accentText)
+ }
+ big(L("录制你的声音")) { rec.start(passage: VoiceReference.passage(for: locale)) }
+ case .recording:
+ HStack(spacing: 12) {
+ Wave(level: rec.level)
+ Text(L("\(Int(rec.seconds)) 秒")).font(.headline).monospacedDigit().foregroundStyle(Ink.ink)
+ Spacer()
+ }
+ big(L("读完了")) { rec.finish() }
+ .disabled(rec.seconds < OwnVoiceRecorder.minSeconds)
+ .opacity(rec.seconds < OwnVoiceRecorder.minSeconds ? 0.5 : 1)
+ case .ready:
+ Text("录好了,先听听像不像").font(.headline).foregroundStyle(Ink.ink)
+ Text("听起来不像或有杂音?换个安静的地方重录一次。录音只存在这台手机上,可随时删除。")
+ .font(.footnote).foregroundStyle(Ink.secondary).fixedSize(horizontal: false, vertical: true)
+ HStack(spacing: 10) {
+ Button { listen() } label: {
+ Label(L("试听"), systemImage: trying ? "stop.fill" : "play.fill").font(.headline)
+ .frame(maxWidth: .infinity).frame(height: 50).background(Color.white, in: Capsule())
+ }
+ .buttonStyle(.plain).foregroundStyle(Ink.ink)
+ Button { rec.start(passage: VoiceReference.passage(for: locale)) } label: {
+ Text("再录一次").font(.headline).frame(maxWidth: .infinity).frame(height: 50).background(Color.white, in: Capsule())
+ }
+ .buttonStyle(.plain).foregroundStyle(Ink.ink)
+ }
+ big(L("用这个声音")) { voice.stop(); done() }
+ }
+ }
+ .padding(20)
+ .background(Ink.ground)
+ .navigationTitle(Text("录制你的声音"))
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) {
+ Button { rec.cancel(); voice.stop(); done() } label: { Image(systemName: "xmark") }
+ .accessibilityLabel(Text("取消"))
+ }
+ }
+ }
+ .interactiveDismissDisabled(rec.phase == .recording)
+ }
+
+ private func big(_ title: String, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ Text(verbatim: title).font(.headline).foregroundStyle(.white)
+ .frame(maxWidth: .infinity).frame(height: 50).background(Ink.ink, in: Capsule())
+ }
+ .buttonStyle(.plain)
+ }
+
+ /// What the other person will hear: a line in their language, in the voice just recorded.
+ private func listen() {
+ if trying { voice.stop(); trying = false; return }
+ trying = true
+ Task {
+ let lang = locale.hasPrefix("en") ? "zh-CN" : "en-US"
+ await voice.speak(VoiceCatalog.sample(for: lang), language: lang, ling: ling, voiceID: VoiceCatalog.cloneOption.id)
+ trying = false
+ }
+ }
+}
+
+/// Records the user reading the passage: 16 kHz mono into a WAV, with a level for the meter;
+/// stops by itself at 30 s. Saved as `VoiceReference` with the passage as what it says (the Mac
+/// transcribes its recording; here the passage is read as shown, and Ming only needs it close).
+@MainActor
+final class OwnVoiceRecorder: ObservableObject {
+ enum Phase: Equatable { case idle, recording, ready, failed(String) }
+
+ @Published private(set) var phase: Phase = .idle
+ @Published private(set) var seconds: Double = 0
+ @Published private(set) var level: Float = 0
+ static let minSeconds = 8.0, maxSeconds = 30.0
+
+ private let engine = AVAudioEngine()
+ private nonisolated(unsafe) var file: AVAudioFile?
+ private nonisolated(unsafe) var converter: AVAudioConverter?
+ private var timer: Timer?
+ private var started = Date()
+ private let url = FileManager.default.temporaryDirectory.appendingPathComponent("cicada-voice.wav")
+ private let format = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 16000, channels: 1, interleaved: true)!
+
+ func start(passage: String) {
+ self.passage = passage
+ Task {
+ guard await AVAudioApplication.requestRecordPermission() else {
+ phase = .failed(L("麦克风没收到声音,请检查麦克风权限"))
+ return
+ }
+ begin()
+ }
+ }
+
+ private func begin() {
+ stopEngine()
+ try? FileManager.default.removeItem(at: url)
+ let session = AVAudioSession.sharedInstance()
+ try? session.setCategory(.playAndRecord, mode: .measurement, options: [.defaultToSpeaker])
+ try? session.setActive(true)
+ let input = engine.inputNode
+ let inFormat = input.inputFormat(forBus: 0)
+ guard inFormat.sampleRate > 0, inFormat.channelCount > 0,
+ let f = try? AVAudioFile(forWriting: url, settings: format.settings, commonFormat: .pcmFormatInt16, interleaved: true),
+ let conv = AVAudioConverter(from: inFormat, to: format) else {
+ phase = .failed(L("麦克风没收到声音,请检查麦克风权限"))
+ return
+ }
+ file = f
+ converter = conv
+ let outFormat = format
+ input.installTap(onBus: 0, bufferSize: 4096, format: inFormat) { [weak self] buffer, _ in
+ guard let self, let conv = self.converter, let file = self.file else { return }
+ let ratio = outFormat.sampleRate / buffer.format.sampleRate
+ guard let out = AVAudioPCMBuffer(pcmFormat: outFormat, frameCapacity: AVAudioFrameCount(Double(buffer.frameLength) * ratio) + 32) else { return }
+ var fed = false
+ conv.convert(to: out, error: nil) { _, status in
+ if fed { status.pointee = .noDataNow; return nil }
+ fed = true
+ status.pointee = .haveData
+ return buffer
+ }
+ try? file.write(from: out)
+ var peak: Float = 0
+ if let ch = buffer.floatChannelData?[0] { for i in 0..<Int(buffer.frameLength) { peak = max(peak, abs(ch[i])) } }
+ Task { @MainActor in self.level = min(1, peak * 2.5) }
+ }
+ do { try engine.start() } catch {
+ input.removeTap(onBus: 0)
+ phase = .failed(L("麦克风没收到声音,请检查麦克风权限"))
+ return
+ }
+ started = Date()
+ seconds = 0
+ phase = .recording
+ let t = Timer(timeInterval: 0.1, repeats: true) { [weak self] _ in
+ MainActor.assumeIsolated {
+ guard let self else { return }
+ self.seconds = Date().timeIntervalSince(self.started)
+ if self.seconds >= Self.maxSeconds { self.finish() }
+ }
+ }
+ timer = t
+ RunLoop.main.add(t, forMode: .common)
+ }
+
+ private var passage = ""
+
+ func finish() {
+ guard phase == .recording else { return }
+ stopEngine()
+ guard seconds >= Self.minSeconds else {
+ phase = .failed(L("录音太短了,请至少朗读 \(Int(Self.minSeconds)) 秒"))
+ return
+ }
+ do {
+ try VoiceReference.save(wav: url, text: passage)
+ try? FileManager.default.removeItem(at: url)
+ debugLog("voice clone: saved \(String(format: "%.1f", VoiceReference.duration)) s")
+ phase = .ready
+ } catch {
+ phase = .failed(L("麦克风没收到声音,请检查麦克风权限"))
+ }
+ }
+
+ func cancel() {
+ stopEngine()
+ phase = .idle
+ try? FileManager.default.removeItem(at: url)
+ }
+
+ private func stopEngine() {
+ timer?.invalidate()
+ timer = nil
+ if engine.isRunning { engine.stop() }
+ engine.inputNode.removeTap(onBus: 0)
+ file = nil
+ converter = nil
+ level = 0
+ }
+}