美文网首页
iOS-swift-音频播放/音乐播放

iOS-swift-音频播放/音乐播放

作者: iOS苦逼开发 | 来源:发表于2017-06-07 17:14 被阅读710次

    创建一个类用来播放音乐,命名为AudioHelper,具体swift代码如下:

    import UIKit
    import AVFoundation
    
    class AudioHelper: NSObject {
        //第一种方式,简单的音频播放
        func playSound(audioUrl: NSURL, isAlert: Bool , playFinish: ()->()) {
            // 一. 获取 SystemSoundID
            //   参数1: 文件路径
            //   参数2: SystemSoundID, 指针
            let urlCF = audioUrl as CFURLRef
            var systemSoundID: SystemSoundID = 0
            AudioServicesCreateSystemSoundID(urlCF, &systemSoundID)
    //        AudioServicesDisposeSystemSoundID(systemSoundID)
            // 二. 开始播放
            if isAlert {
                // 3. 带振动播放, 可以监听播放完成(模拟器不行)
                AudioServicesPlayAlertSound(systemSoundID)
            }else {
                // 3. 不带振动播放, 可以监听播放完成
                AudioServicesPlaySystemSound(systemSoundID)
            }
            playFinish()
            
        }
        
        //第二种使用AVAudioPlayer播放
        // 获取音频会话
        let session = AVAudioSession.sharedInstance()
        var player: AVAudioPlayer?
        var currentURL : NSURL?
        let playFinish = "playFinsh"
        
        override init() {
            super.init()
            do{
                //  设置会话类别
                try session.setCategory(AVAudioSessionCategoryPlayback)
                //  激活会话
                try session.setActive(true)
            }catch {
                print(error)
                return
            }
        }
        
        //paly music
        func playMusic(filePath: String) {
            guard let url = NSURL(string: filePath) else {
                return//url不存在
            }
            do{
                //AVAudioSessionCategoryPlayback扬声器模式
                try session.setCategory(AVAudioSessionCategoryPlayback)
            }catch {
                print(error)
                return
            }
           //如果播放的音乐与之前的一样,则继续播放
            if currentURL == url {
                player?.play()
                return
            }
            do {
                player = try AVAudioPlayer(data: NSFileManager.defaultManager().contentsAtPath(filePath)!)
                currentURL = url
                player?.delegate = self
                //开启红外感知功能
    //            UIDevice.currentDevice().proximityMonitoringEnabled = true
    //            NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(proxumityStateChange), name: "UIDeviceProximityStateDidChangeNotification", object: nil)
                player?.prepareToPlay()
                player?.play()
                print("播放成功,文件路径 ==\(url)")
            }catch {
                print(error)
                return
            }
        }
        
         //配合红外感知功能
    //    func proxumityStateChange(notification:NSNotification){
    //        if UIDevice.currentDevice().proximityState == true{
    //            //使用听筒模式,屏幕变暗
    //            do{
    //                try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
    //            }catch {
    //                print(error)
    //                return
    //            }
    //        }else{
    //            //使用扬声器模式
    //            do{
    //                try session.setCategory(AVAudioSessionCategoryPlayback)
    //            }catch {
    //                print(error)
    //                return
    //            }
    //        }
    //    }
        
        // 暂停当前歌曲/pause current music
        func pauseCurrentMusic() -> () {
            player?.pause()
        }
        
        // 继续播放当前歌曲/continue to play current music
        func resumeCurrentMusic() -> () {
            player?.play()
        }
        
        // 播放到指定时间/play music to specified time
        func seekToTime(time: NSTimeInterval) -> () {
            player?.currentTime = time
        }
        
        
        class func getFormatTime(timeInterval: NSTimeInterval) -> String {
            let min = Int(timeInterval) / 60
            let sec = Int(timeInterval) % 60
            let timeStr = String(format: "%02d:%02d", min, sec)
            return timeStr
        }
        
        class func getTimeInterval(formatTime: String) -> NSTimeInterval {
            // 00:00.89 == formatTime
            let minSec = formatTime.componentsSeparatedByString(":")
            if minSec.count == 2 {
                let min = NSTimeInterval(minSec[0]) ?? 0
                let sec = NSTimeInterval(minSec[1]) ?? 0
                return min * 60 + sec
            }
            return 0
        }
    }
    
    extension AudioHelper: AVAudioPlayerDelegate {
        //播放完成后的回调
        func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
            print("播放完成")
            NSNotificationCenter.defaultCenter().postNotificationName(playFinish, object: nil)
            self.currentURL = nil
        }
    }
    

    然后外界调用的话是这样的:

    self.audioPlayer = AudioHelper()
    self.audioPlayer.playMusic(filePath)
    

    相关文章

      网友评论

          本文标题:iOS-swift-音频播放/音乐播放

          本文链接:https://www.haomeiwen.com/subject/zolafxtx.html