//
//  SpeakSpeechSynthesizer.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/7.
//

import UIKit
import AVFAudio

class SpeakSpeechSynthesizer : NSObject,AVSpeechSynthesizerDelegate {

    static let share = SpeakSpeechSynthesizer()
    
    private var synthesizer = AVSpeechSynthesizer()
    
    func loadData() -> Void {
        self.synthesizer.delegate = self
    }
    
    func speakText(_ text:String ,language:String = "en-US") {
        DispatchQueue.global(qos: .utility).async {
            guard text.count > 0 else { return }
            let utterance = AVSpeechUtterance(string: text)
            utterance.voice = AVSpeechSynthesisVoice(language: language)
            utterance.rate = 0.5
            utterance.volume = 1
            // 设置动画监听
            self.synthesizer.speak(utterance)
        }
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        // 朗读完成，恢复Idle动画
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
        // 可以在这里根据朗读进度切换不同的动画

    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
        Print("开始\(CACurrentMediaTime())")
    }
    
}
