//
//  TSAudioPlayer.swift
//  Girly
//
//  Created by 100Years on 2025/1/9.
//

import AVFoundation

class TSAudioPlayer {
    private var audioPlayer: AVAudioPlayer?
    private var isLooping: Bool = false
    
    /// 初始化播放器
    /// - Parameter url: 音频文件的 URL
    init?(url: URL) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.prepareToPlay()
        } catch {
            print("音频文件加载失败: \(error.localizedDescription)")
            return nil
        }
    }
    
    /// 开始播放音频
    func play() {
        guard let audioPlayer = audioPlayer else { return }
        audioPlayer.numberOfLoops = isLooping ? -1 : 0
        audioPlayer.play()
    }
    
    /// 暂停播放音频
    func pause() {
        audioPlayer?.pause()
    }
    
    /// 停止并销毁播放器
    func stop() {
        audioPlayer?.stop()
        audioPlayer = nil
    }
    
    /// 设置是否重复播放
    /// - Parameter loop: 是否循环播放
    func setLoop(_ loop: Bool) {
        isLooping = loop
        audioPlayer?.numberOfLoops = loop ? -1 : 0
    }
    
    /// 设置音量
    /// - Parameter volume: 音量大小 (0.0 静音, 1.0 最大)
    func setVolume(_ volume: Float) {
        audioPlayer?.volume = max(0.0, min(volume, 1.0))
    }
    
    deinit {
        stop()
    }
}
