Swift-AVAudioPlayer本地音频播放

import UIKit
import Foundation

class PublicFunction: NSObject {
    //MARK:GCD实现定时器
    ///
    /// - Parameters:
    ///   - timeInterval: 间隔时间
    ///   - handler: 事件
    ///   - needRepeat: 是否重复
    static func dispatchTimer(timeInterval: Double, handler: @escaping (DispatchSourceTimer?) -> Void, needRepeat: Bool) {
        let timer = DispatchSource.makeTimerSource(flags: [], queue: DispatchQueue.main)
        timer.schedule(deadline: .now(), repeating: timeInterval)
        timer.setEventHandler {
            DispatchQueue.main.async {
                if needRepeat {
                    handler(timer)
                } else {
                    timer.cancel()
                    handler(nil)
                }
            }
        }
        timer.resume()
    }
}
import UIKit
import Foundation

class PublicFunction: NSObject {
    //MARK:document文档目录
    static func documentPath() -> String {
        let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as String
        return documentPath
    }

    //MARK:文件路径
    static func downloadDirectory(path:String) -> String {
        let downloadFile = PublicFunction.documentPath() + "/\(path)/"
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: downloadFile) == false {
            do {
                try fileManager.createDirectory(atPath: downloadFile, withIntermediateDirectories: true, attributes: nil)
            } catch {
                print(error)
            }
        }
        return downloadFile
    }
}
import UIKit
import AVFoundation

class LocalAudioPlayerTool: NSObject,AVAudioPlayerDelegate {
    
    //单列
    static let sharedAudioPlayer = LocalAudioPlayerTool()
    //播放器
    var audioPlayer:AVAudioPlayer = AVAudioPlayer()
    //播放完毕
    var completePlayingBlock:funcBlock?
    
    //MARK:初始化播放器
    func playAudioWithPath(audioPath:String) {
        let session = AVAudioSession.sharedInstance()
        //在音频播放前,首先创建一个异常捕捉语句
        do {
            //启动音频会话管理,此时会阻断后台音乐播放
            try session.setActive(true)
            //设置音频播放类别,表示该应用仅支持音频播放
            try session.setCategory(AVAudioSession.Category.playback)
            
            //将字符串路径转化为网址路径
            let soundUrl = URL(fileURLWithPath: audioPath)
            
            try audioPlayer = AVAudioPlayer(contentsOf:soundUrl)
            //为音频播放做好准备
            audioPlayer.prepareToPlay()
            //设置音量
            audioPlayer.volume = 1.0
            //是否循环播放
            //audioPlayer.numberOfLoops = -1
            audioPlayer.delegate = self
        } catch {
            print(error)
        }
    }
    
    //MARK:开始播放
    func playAudio() {
        if audioPlayer.duration > 0 {
            audioPlayer.play()
        }
    }
    
    //MARK:暂停播放
    func pauseAudio() {
        if audioPlayer.duration > 0 {
            audioPlayer.pause()
        }
    }
    
    //MARK:停止播放
    func stopAudio() {
        if audioPlayer.duration > 0 {
            audioPlayer.stop()
        }
        completePlayingBlock?()
    }
    
    //MARK:播放时长
    func currentTime() -> (TimeInterval) {
        return audioPlayer.currentTime
    }
    
    //MARK:音频时长
    func duration() -> (TimeInterval) {
        return audioPlayer.duration
    }
    
    //MARK:修改播放进度
    func playWithPercent(percent:Double) {
        if audioPlayer.duration > 0 {
            audioPlayer.currentTime = audioPlayer.duration * percent
        }
    }
    
    //MARK:修改音量大小
    func updateVolume(volume:Float) {
        audioPlayer.volume = volume
    }
    
    //MARK:播放进度
    func percent() -> (Float) {
        var percent:Float = 0
        if audioPlayer.duration > 0  {
            percent = Float(audioPlayer.currentTime/audioPlayer.duration)
        }
        return percent
    }
    
    //MARK:播放完毕
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        self.stopAudio()
    }
}
//单列初始化
let savePath = PublicFunction.downloadDirectory(path: "download") + "111.mp3"
LocalAudioPlayerTool.sharedAudioPlayer.playAudioWithPath(audioPath: savePath)
//开始播放
LocalAudioPlayerTool.sharedAudioPlayer.playAudio()
//暂停播放
LocalAudioPlayerTool.sharedAudioPlayer.pauseAudio()
//拖动修改进度
LocalAudioPlayerTool.sharedAudioPlayer.playWithPercent(percent: Double(sender.value/100))
//MARK:更新播放进度
func updateAudioProgress() {
    PublicFunction.dispatchTimer(timeInterval: 1, handler: { _ in
        print("播放进度---\(LocalAudioPlayerTool.sharedAudioPlayer.percent())")
    }
}

你可能感兴趣的:(Swift-AVAudioPlayer本地音频播放)