//
//  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 speakText(_ text:String ,language:String = "en-US") {
        guard text.count > 0 else { return }
        let utterance = AVSpeechUtterance(string: text)
        utterance.voice = AVSpeechSynthesisVoice(language: language)
        utterance.rate = 0.5
        utterance.volume = 1
        // 设置动画监听
        synthesizer.delegate = self
        synthesizer.speak(utterance)
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance: AVSpeechUtterance) {
        // 朗读完成，恢复Idle动画
        DispatchQueue.main.async {
            Print("结束\(CACurrentMediaTime())")
        }
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, willSpeakRangeOfSpeechString characterRange: NSRange, utterance: AVSpeechUtterance) {
        // 可以在这里根据朗读进度切换不同的动画
//        let progress = Double(characterRange.location) / Double(utterance.speechString.count)
//        if progress > 0.7 {
//            Print("0.7")
//        }
    }
    
    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didStart utterance: AVSpeechUtterance) {
        Print("开始\(CACurrentMediaTime())")
    }
    
}
