SPB Git

Repository Public

SpeechPlayer.swift 2.5 KB 65 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Features/Voice/SpeechPlayer.swift4//  Description: Reads an answer aloud with the backend's text-to-speech endpoint and AVAudioPlayer.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import AVFoundation11import Observation1213@MainActor14@Observable15final class SpeechPlayer: NSObject, AVAudioPlayerDelegate {16    enum State: Equatable { case idle, loading(String), playing(String) }17    private(set) var state: State = .idle18    var lastError: String?1920    @ObservationIgnored private let api: ChatAPI21    @ObservationIgnored private var player: AVAudioPlayer?22    @ObservationIgnored private var task: Task<Void, Never>?2324    init(api: ChatAPI) { self.api = api }2526    func isActive(_ messageId: String) -> Bool { state == .loading(messageId) || state == .playing(messageId) }2728    /// Starts reading a message, or stops if it is the one being read. The server accepts 4 000 characters per request.29    func toggle(messageId: String, text: String, voice: String) {30        if isActive(messageId) { stop(); return }31        stop()32        let clean = text.trimmingCharacters(in: .whitespacesAndNewlines)33        guard !clean.isEmpty else { return }34        state = .loading(messageId); lastError = nil35        let api = api36        task = Task { [weak self] in37            do {38                let audio = try await api.speech(text: clean, voice: voice)39                guard !Task.isCancelled, let self else { return }40                try AVAudioSession.sharedInstance().setCategory(.playback, mode: .spokenAudio, options: [.duckOthers])41                try AVAudioSession.sharedInstance().setActive(true)42                let p = try AVAudioPlayer(data: audio)43                p.delegate = self44                self.player = p45                p.play()46                self.state = .playing(messageId)47            } catch {48                guard !Task.isCancelled else { return }49                self?.state = .idle50                self?.lastError = (error as? APIError)?.message ?? String(localized: "Lecture audio impossible.")51            }52        }53    }5455    func stop() {56        task?.cancel(); task = nil57        player?.stop(); player = nil58        if state != .idle { state = .idle; try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) }59    }6061    nonisolated func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {62        Task { @MainActor in self.stop() }63    }64}65
Files main
Menu

Theme