| | |
| | | import AVFAudio |
| | | |
| | | |
| | | protocol VoicePlayerDelegate{ |
| | | func playComplete() |
| | | } |
| | | |
| | | /// 音频播放器 |
| | | class VoicePlayer:NSObject{ |
| | | /// 缓存地址 |
| | | private let voiceCacheDirectory = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.appendingPathComponent("voices") |
| | | private static var _sharedInstance: VoicePlayer? |
| | | private var player:AVAudioPlayer? |
| | | |
| | | var delegate:VoicePlayerDelegate? |
| | | |
| | | //是否正在播放 |
| | | var isPlaying:Bool{return player?.isPlaying ?? false} |
| | |
| | | |
| | | |
| | | /// 单例 |
| | | /// - Returns: <#description#> |
| | | class func share() -> VoicePlayer { |
| | | guard let instance = _sharedInstance else { |
| | | _sharedInstance = VoicePlayer() |
| | |
| | | func playerAt(url:String?){ |
| | | guard let u = url else {return} |
| | | if player?.isPlaying ?? false{ |
| | | VoicePlayer.share().playComplete?() //先通知完成播放 |
| | | player?.stop() |
| | | self.playComplete?() //先通知完成播放 |
| | | } |
| | | |
| | | //文件存在:直接播放缓存路径的语音 |
| | |
| | | extension VoicePlayer:AVAudioPlayerDelegate{ |
| | | func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { |
| | | VoicePlayer.share().playComplete?() |
| | | delegate?.playComplete() |
| | | } |
| | | |
| | | func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: (any Error)?) { |