|
| 1 | +import AVFoundation |
| 2 | +import Foundation |
| 3 | + |
| 4 | +@MainActor |
| 5 | +final class FloatingBarVoicePlaybackService: NSObject { |
| 6 | + static let shared = FloatingBarVoicePlaybackService() |
| 7 | + |
| 8 | + static let devAPIKeyDefaultsKey = "dev_elevenlabs_api_key" |
| 9 | + static let devVoiceIDDefaultsKey = "dev_elevenlabs_voice_id" |
| 10 | + |
| 11 | + nonisolated private static let defaultVoiceID = "21m00Tcm4TlvDq8ikWAM" // Rachel |
| 12 | + nonisolated private static let defaultModelID = "eleven_multilingual_v2" |
| 13 | + |
| 14 | + private var playbackTask: Task<Void, Never>? |
| 15 | + private var audioPlayer: AVAudioPlayer? |
| 16 | + private let speechSynthesizer = AVSpeechSynthesizer() |
| 17 | + |
| 18 | + private override init() {} |
| 19 | + |
| 20 | + func playResponseIfEnabled(_ message: ChatMessage?) { |
| 21 | + guard AnalyticsManager.isDevBuild else { return } |
| 22 | + guard ShortcutSettings.shared.floatingBarVoiceAnswersEnabled else { return } |
| 23 | + |
| 24 | + let text = Self.cleanedPlaybackText(from: message) |
| 25 | + guard !text.isEmpty, Self.shouldSpeak(text) else { return } |
| 26 | + |
| 27 | + let defaults = UserDefaults.standard |
| 28 | + guard let apiKey = defaults.string(forKey: Self.devAPIKeyDefaultsKey)?.trimmingCharacters(in: .whitespacesAndNewlines), |
| 29 | + !apiKey.isEmpty else { |
| 30 | + playSystemFallback(text) |
| 31 | + return |
| 32 | + } |
| 33 | + |
| 34 | + let voiceID = defaults.string(forKey: Self.devVoiceIDDefaultsKey)? |
| 35 | + .trimmingCharacters(in: .whitespacesAndNewlines) |
| 36 | + let resolvedVoiceID = (voiceID?.isEmpty == false) ? voiceID! : Self.defaultVoiceID |
| 37 | + |
| 38 | + stop() |
| 39 | + playbackTask = Task { [weak self] in |
| 40 | + do { |
| 41 | + let audioData = try await Self.synthesizeSpeech(text: text, apiKey: apiKey, voiceID: resolvedVoiceID) |
| 42 | + try Task.checkCancellation() |
| 43 | + await MainActor.run { |
| 44 | + self?.startPlayback(audioData) |
| 45 | + } |
| 46 | + } catch is CancellationError { |
| 47 | + } catch { |
| 48 | + await MainActor.run { |
| 49 | + log("FloatingBarVoicePlaybackService: ElevenLabs playback failed, falling back to system voice: \(error.localizedDescription)") |
| 50 | + self?.playSystemFallback(text) |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + func stop() { |
| 57 | + playbackTask?.cancel() |
| 58 | + playbackTask = nil |
| 59 | + audioPlayer?.stop() |
| 60 | + audioPlayer = nil |
| 61 | + speechSynthesizer.stopSpeaking(at: .immediate) |
| 62 | + } |
| 63 | + |
| 64 | + private func startPlayback(_ data: Data) { |
| 65 | + do { |
| 66 | + let player = try AVAudioPlayer(data: data) |
| 67 | + player.prepareToPlay() |
| 68 | + player.play() |
| 69 | + audioPlayer = player |
| 70 | + } catch { |
| 71 | + log("FloatingBarVoicePlaybackService: could not start audio playback: \(error.localizedDescription)") |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + private func playSystemFallback(_ text: String) { |
| 76 | + speechSynthesizer.stopSpeaking(at: .immediate) |
| 77 | + let utterance = AVSpeechUtterance(string: text) |
| 78 | + utterance.rate = 0.47 |
| 79 | + utterance.pitchMultiplier = 1.02 |
| 80 | + utterance.volume = 1.0 |
| 81 | + utterance.voice = preferredSystemVoice() |
| 82 | + speechSynthesizer.speak(utterance) |
| 83 | + } |
| 84 | + |
| 85 | + private func preferredSystemVoice() -> AVSpeechSynthesisVoice? { |
| 86 | + let preferredNames = ["Samantha", "Karen", "Moira"] |
| 87 | + for name in preferredNames { |
| 88 | + if let voice = AVSpeechSynthesisVoice.speechVoices().first(where: { $0.name.localizedCaseInsensitiveContains(name) }) { |
| 89 | + return voice |
| 90 | + } |
| 91 | + } |
| 92 | + return AVSpeechSynthesisVoice(language: "en-US") |
| 93 | + } |
| 94 | + |
| 95 | + private nonisolated static func synthesizeSpeech(text: String, apiKey: String, voiceID: String) async throws -> Data { |
| 96 | + var request = URLRequest(url: URL(string: "https://api.elevenlabs.io/v1/text-to-speech/\(voiceID)")!) |
| 97 | + request.httpMethod = "POST" |
| 98 | + request.setValue("application/json", forHTTPHeaderField: "Content-Type") |
| 99 | + request.setValue("audio/mpeg", forHTTPHeaderField: "Accept") |
| 100 | + request.setValue(apiKey, forHTTPHeaderField: "xi-api-key") |
| 101 | + request.timeoutInterval = 45 |
| 102 | + |
| 103 | + let body = ElevenLabsSpeechRequest( |
| 104 | + text: text, |
| 105 | + modelID: defaultModelID, |
| 106 | + outputFormat: "mp3_44100_128", |
| 107 | + voiceSettings: .init( |
| 108 | + stability: 0.42, |
| 109 | + similarityBoost: 0.82, |
| 110 | + style: 0.22, |
| 111 | + useSpeakerBoost: true |
| 112 | + ) |
| 113 | + ) |
| 114 | + request.httpBody = try JSONEncoder().encode(body) |
| 115 | + |
| 116 | + let (data, response) = try await URLSession.shared.data(for: request) |
| 117 | + guard let httpResponse = response as? HTTPURLResponse else { |
| 118 | + throw FloatingBarVoicePlaybackError.invalidResponse |
| 119 | + } |
| 120 | + guard (200 ..< 300).contains(httpResponse.statusCode) else { |
| 121 | + let errorBody = String(data: data.prefix(300), encoding: .utf8) ?? "Unknown error" |
| 122 | + throw FloatingBarVoicePlaybackError.requestFailed(statusCode: httpResponse.statusCode, body: errorBody) |
| 123 | + } |
| 124 | + return data |
| 125 | + } |
| 126 | + |
| 127 | + private nonisolated static func cleanedPlaybackText(from message: ChatMessage?) -> String { |
| 128 | + guard let message else { return "" } |
| 129 | + |
| 130 | + let baseText: String |
| 131 | + if !message.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { |
| 132 | + baseText = message.text |
| 133 | + } else { |
| 134 | + baseText = message.contentBlocks.compactMap { block in |
| 135 | + switch block { |
| 136 | + case .text(_, let text): |
| 137 | + return text |
| 138 | + case .discoveryCard(_, let title, let summary, _): |
| 139 | + return "\(title). \(summary)" |
| 140 | + case .toolCall, .thinking: |
| 141 | + return nil |
| 142 | + } |
| 143 | + }.joined(separator: "\n\n") |
| 144 | + } |
| 145 | + |
| 146 | + let collapsedWhitespace = baseText.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression) |
| 147 | + return collapsedWhitespace.trimmingCharacters(in: .whitespacesAndNewlines) |
| 148 | + } |
| 149 | + |
| 150 | + private nonisolated static func shouldSpeak(_ text: String) -> Bool { |
| 151 | + let lowercased = text.lowercased() |
| 152 | + if lowercased == "failed to get a response. please try again." { |
| 153 | + return false |
| 154 | + } |
| 155 | + if lowercased.hasPrefix("⚠️") || lowercased.hasPrefix("warning:") { |
| 156 | + return false |
| 157 | + } |
| 158 | + return true |
| 159 | + } |
| 160 | +} |
| 161 | + |
| 162 | +private struct ElevenLabsSpeechRequest: Encodable { |
| 163 | + let text: String |
| 164 | + let modelID: String |
| 165 | + let outputFormat: String |
| 166 | + let voiceSettings: ElevenLabsVoiceSettings |
| 167 | + |
| 168 | + enum CodingKeys: String, CodingKey { |
| 169 | + case text |
| 170 | + case modelID = "model_id" |
| 171 | + case outputFormat = "output_format" |
| 172 | + case voiceSettings = "voice_settings" |
| 173 | + } |
| 174 | +} |
| 175 | + |
| 176 | +private struct ElevenLabsVoiceSettings: Encodable { |
| 177 | + let stability: Double |
| 178 | + let similarityBoost: Double |
| 179 | + let style: Double |
| 180 | + let useSpeakerBoost: Bool |
| 181 | + |
| 182 | + enum CodingKeys: String, CodingKey { |
| 183 | + case stability |
| 184 | + case similarityBoost = "similarity_boost" |
| 185 | + case style |
| 186 | + case useSpeakerBoost = "use_speaker_boost" |
| 187 | + } |
| 188 | +} |
| 189 | + |
| 190 | +private enum FloatingBarVoicePlaybackError: LocalizedError { |
| 191 | + case invalidResponse |
| 192 | + case requestFailed(statusCode: Int, body: String) |
| 193 | + |
| 194 | + var errorDescription: String? { |
| 195 | + switch self { |
| 196 | + case .invalidResponse: |
| 197 | + return "Invalid ElevenLabs response" |
| 198 | + case .requestFailed(let statusCode, let body): |
| 199 | + return "ElevenLabs request failed (\(statusCode)): \(body)" |
| 200 | + } |
| 201 | + } |
| 202 | +} |
0 commit comments