美文网首页
音频播放AVPlayer

音频播放AVPlayer

作者: 写啥呢 | 来源:发表于2016-09-20 18:25 被阅读0次

    音频播放器AVaudioPlayer(专门负责音频)

    import UIKit
    import AVFoundation
    class AnalyseMedia: NSObject {
    
        //注:当前方法中不涉及任何类的属性的时候,可以将这个方法声明称类型方法,方便直接使用类名来调用
        //分析歌曲信息
        static func analyseMusic(name:String)->MediaModel{
            
            //拿到路径
            let url = NSURL.init(fileURLWithPath: NSBundle.mainBundle().pathForResource(name, ofType: nil)!)
            //1.创建媒体解析器对象
            //参数:需要解析的媒体资源的路径
            let asset = AVURLAsset.init(URL: url)
            
            //2.获取格式
            let format = asset.availableMetadataFormats.first
            
            //3.根据指定的格式去获取信息
            let infoArray = asset.metadataForFormat(format!)
            
            //4.遍历数组获取所有的信息
            //a.创建模型用来获取所有的相关信息
            let model = MediaModel()
            //b.遍历拿到不同的信息
            for item in infoArray {
                //c.通过判断commonKey属性,去获取不同的信息
                //1.演唱者
                if item.commonKey == "artist" {
                    model.artist = item.value as! String
                }
                
                //2.专辑名
                if item.commonKey == "albumName" {
                    
                    model.albumName = item.value as! String
                }
                
                //3.歌曲名
                if item.commonKey == "title" {
                    
                    model.title = item.value as! String
                }
                
                //4.插图
                if item.commonKey == "artwork" {
                    
                    let data = item.value as! NSData
                    model.artwork = UIImage.init(data: data)
                }
                
            }
            
            //将信息返回
            return model
            
        }
        
    
    
    class MediaModel: NSObject {
        
        ///演唱者
        var artist = ""
        ///专辑名
        var albumName = ""
        ///歌曲名
        var title = ""
        ///插图
        var artwork:UIImage? = nil
        
    }
    
    

    ViewController 中的代码

    import UIKit
    
    //使用AVAudioPlayer需要包含AVFoundation库文件
    import AVFoundation
    
    
    class ViewController: UIViewController {
        
        //MARK: - 属性
        //注意:播放器对象必须声明成属性
        var player:AVAudioPlayer? = nil
        @IBOutlet weak var slider: UISlider!
        
        @IBOutlet weak var imageView: UIImageView!
        
        //MARK: - 生命周期
        override func viewDidLoad() {
            super.viewDidLoad()
            
            self.creatPlayer("蓝莲花.mp3")
            
            //添加定时器
            NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateSlider", userInfo: nil, repeats: true)
            
            
        }
        
    }
    
    //MARK: - 创建播放器
    extension ViewController{
    
        func creatPlayer(name:String) {
            
            //1.创建音频路径(网络地址/本地)
            let path = NSBundle.mainBundle().pathForResource(name, ofType: nil)
            //将本地路径转换成url
            let url = NSURL.init(fileURLWithPath: path!)
            
            //将网络地址转换成url
            //let url = NSURL.init(string: <#T##String#>)
            
            //2.根据url创建播放器对象
            do{
            
                let tPlyer = try AVAudioPlayer.init(contentsOfURL: url)
                self.player = tPlyer
            }catch{
            
                print("音频路径不对")
            }
            
            
            //3.准备播放
            self.player?.prepareToPlay()
            
            //4.开始播放。
            //音频播放器实质没有任何界面的,只是用来播放声音
            //self.player?.play()
            
            //5.音量(范围:0-1)
            self.player?.volume = 0.5
            
            //6.设置代理
            self.player?.delegate = self
            
            //7.显示图片
            let model = AnalyseMedia.analyseMusic(name)
            self.imageView.image = model.artwork
        }
    }
    
    //MARK: - PlayerDelegate
    extension ViewController:AVAudioPlayerDelegate{
    
        //已经结束播放的时候会自动调用
        func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool){
        
            //切换到下一首(实质是重新创建一个对应的播放器)
            self.creatPlayer("江南-style.mp3")
            //切换后需要手动开始播放
            self.player?.play()
        }
    }
    
    //MARK: - 播放进度
    extension ViewController{
        
        //刷新进度条
        func updateSlider() {
            
            //拿到当前时间
            let time = Float((self.player?.currentTime)!)
            //拿到总时间
            let duration = Float((self.player?.duration)!)
            
            self.slider.value = time/duration
        }
    
        @IBAction func sliderAction(sender: UISlider) {
            
            //拿到当前播放器播放的音乐的总时间
            let duration = self.player?.duration
            
            //设置当前播放时间
            self.player?.currentTime = duration! * Double(sender.value)
            
        }
        
    }
    
    //MARK: - 音量
    extension ViewController{
    
        @IBAction func stepAction(sender: UIStepper) {
            
            self.player?.volume = Float(sender.value)
        }
        
    }
    //MARK: - 音频的播放和暂停
    extension ViewController{
    
        @IBAction func playAction(sender: UIButton) {
            
            //判断当前播放器是否正在播放音乐
            if self.player?.playing == true {
                //5.暂停
                //self.player?.stop()
                self.player?.pause()
                
                sender.setTitle("播放", forState: .Normal)
                
            }else{
            
                //4.开始播放
                self.player?.play()
                //让按钮显示暂停
                sender.setTitle("暂停", forState: .Normal)
            }
        }
        
    }
    
    

    AVPlayer音频

    class ViewController: UIViewController {
    
        //MARK: - 属性
        lazy var player:AVPlayer = {
        
            return self.creatPlayer()
        }()
        //进度条
        @IBOutlet weak var slider: UISlider!
        //图片
        @IBOutlet weak var imageView: UIImageView!
        //歌词解析器
        let lyricManager = YTAnalysis()
        
        @IBOutlet weak var lyricLabel: UILabel!
        
        
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            //1.注册观察者,去观察播放器播放结束的时刻(AVPlayer在播放完成后,消息中心会自动发送播放完成对应的消息)
            //AVPlayerItemDidPlayToEndTimeNotification ->消息名
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "finishedPlay", name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
            
            //2.获取播放器的播放进度
            //参数1:时间间隔(每隔多长时间获取一次播放进度),1秒
            //参数2:执行参数3中的任务的队列
            //参数3:每隔1秒需要执行的任务
            self.player.addPeriodicTimeObserverForInterval(CMTimeMake(1, 10), queue: dispatch_get_main_queue()) { (cmCurrent) in
                //闭包中的参数:当前时间(CMTime)
                
                //a.总的时间
                let cmDuration = self.player.currentItem?.duration
                //秒对应的总时间
                let duration = Float((cmDuration?.value)!) / Float((cmDuration?.timescale)!)
                
                //b.秒对应的当前时间
                let current = Float(cmCurrent.value) / Float(cmCurrent.timescale)
                
                //计算百分比
                self.slider.value = current / duration
                
                //获取指定时间对应的歌词
                let str = self.lyricManager.getLyricWithTime(Double(current))
                
                self.lyricLabel.text = str
                
            }
            
            
            
        }
    
    }
    
    //MARK: - 播放进度
    extension ViewController{
    
        @IBAction func sliderAction(sender: UISlider) {
            
            //1.CMTime基础:
            //总时间:总帧数/每一秒播放的帧数
            //当前时间:当前帧数/每一秒播放的帧数
            //将播放器定位到指定的时间
            //在AVPlayer中所有的时间都是以CMTime来确定
            //CMTime中的value属性代表帧数,timeScale代表每一秒播放的帧数。一个CMTime变量确定的真正的时间是value/timescale
            //确定一个第10秒
            //let cmTime = CMTimeMake(100, 10)
            //let cmTime = CMTimeMake(10, 1)
            
            
            //2.定位到指定进度
            //a.拿到当前播放源的总时间(CMTime)
            let cmDuration =  self.player.currentItem?.duration
            //转换成秒单位时间
            let duration = Double((cmDuration?.value)!) / Double((cmDuration?.timescale)!)
            
            //b.根据进度条计算出当前时间
            let currentTime = duration * Double(sender.value)
            
            //c.定位到指定的位置
            self.player.seekToTime(CMTimeMake(Int64(currentTime), 1))
            
        }
        
    }
    
    //MARK: - 切换播放源
    extension ViewController{
    
        func finishedPlay() {
            
            print("完成")
            self.changeItem("北京北京")
        }
        
        func changeItem(name:String){
            
            //1.创建新的播放源
            let url = NSURL.init(fileURLWithPath: NSBundle.mainBundle().pathForResource(name, ofType:"mp3")!)
            let newItem = AVPlayerItem.init(URL: url)
            
            //2.替换播放源
            self.player.replaceCurrentItemWithPlayerItem(newItem)
            
            //3.开始播放
            self.player.play()
            
            //4.更新图片
            self.imageView.image = AnalyseMedia.analyseMusic(name+".mp3").artwork
        }
    }
    
    
    //MARK: - 控制音量和速度
    extension ViewController{
    
        @IBAction func rateAction(sender: UIStepper) {
            
            //改变播放速度(0.5-2)
            self.player.rate = Float(sender.value)
            
        }
        
        @IBAction func volumeAction(sender: UIStepper) {
            
            //改变音量(0-1)
            self.player.volume = Float(sender.value)
        }
        
    }
    
    //MARK: - 播放和暂停
    extension ViewController{
    
        @IBAction func playAction(sender: UIButton) {
            
            if sender.currentTitle == "播放" || sender.currentTitle == "继续" {
                
                //1.开始播放
                self.player.play()
                
                sender.setTitle("暂停", forState: .Normal)
            }else{
            
                //2.暂停播放
                self.player.pause()
                
                sender.setTitle("继续", forState: .Normal)
            }
        }
        
    }
    
    //MARK: - 创建播放器
    extension ViewController{
    
        func creatPlayer()->AVPlayer{
            
            //1.获取播放路径
            let url = NSURL.init(fileURLWithPath: NSBundle.mainBundle().pathForResource("蓝莲花.mp3", ofType: nil)!)
            
            //2.创建播放源
            let item = AVPlayerItem.init(URL: url)
            
            //3.创建播放器对象
            let tPlayer = AVPlayer.init(playerItem: item)
            
            //4.获取歌曲信息
            self.imageView.image = AnalyseMedia.analyseMusic("蓝莲花.mp3").artwork
            
            //5.解析歌词
            self.lyricManager.analysisLyricWithPath(NSBundle.mainBundle().pathForResource("蓝莲花.lrc", ofType: nil))
            
            return tPlayer
        }
    }
    
    

    AVPlayer视频播放

    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
        //MARK: - 属性
        lazy var player:AVPlayer = {
        
            return self.creatPlayer()
        }()
        
    
        override func viewDidLoad() {
            super.viewDidLoad()
            
            //1.开始播放
            self.player.play()
            
            
            self.creatPlayView()
        }
    
    }
    
    //MARK: - 添加播放器的播放界面
    extension ViewController{
    
        func creatPlayView() {
            
            //AVPlayerLayer:专门负责显示AVPlayer中的视频图像的类
            //1.创建播放页面对象
            let playLayer = AVPlayerLayer.init(player: self.player)
            //2.设置frame
            playLayer.frame = CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 300)
            //3.添加到界面上
            self.view.layer.addSublayer(playLayer)
            
            //4.添加暂停和播放按钮
            let button = UIButton.init(frame: CGRectMake(0, 0, 30, 30))
            button.center = CGPointMake(self.view.center.x, 220)
            button.backgroundColor = UIColor.init(white: 0.2, alpha: 0.6)
            button.addTarget(self, action: "stop", forControlEvents: .TouchDown)
            self.view.addSubview(button)
        }
        
        func stop() {
            
            self.player.pause()
        }
        
    }
    
    
    
    //MARK: - 创建播放器
    extension ViewController{
    
        func creatPlayer()->AVPlayer {
            
            //1.创建播放源
            //本地视频
            //let url = NSURL.init(fileURLWithPath: NSBundle.mainBundle().pathForResource("MovieTest.mp4", ofType: nil)!)
            //网络视频
            let url = NSURL.init(string: "http://otmv.alicdn.com/new/mv_1_6/23/77/2306cd13e3dde338b53f404ece43a277.mp4?k=7125c1a8f09b70bb&t=1451830866")
            let item = AVPlayerItem.init(URL: url!)
            
            //2.根据播放源创建播放器
            let tPlayer = AVPlayer.init(playerItem: item)
            
            //3.返回
            return tPlayer
        }
    }
    
    
    

    MPMoviePlayerController

    import UIKit
    import MediaPlayer
    
    class ViewController: UIViewController {
        
        //MARK: - 属性
        var playerController:MPMoviePlayerController? = nil
        
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            //0.创建播放源路径
            //let url = NSURL.init(fileURLWithPath: NSBundle.mainBundle().pathForResource("MovieTest.mp4", ofType: nil)!)
            
            let url = NSURL.init(string: "http://123.56.17.178:8080/mgtv.php?vid=b656XJyg5Y85HIOq+eW/kYGtHIMX7lYiFBntHHuD2IsVs9Sa")
           
            //1.创建对象
            self.playerController = MPMoviePlayerController.init(contentURL: url)
            //2.设置播放器界面的大小
            self.playerController?.view.frame = self.view.bounds
            //3.添加播放器界面
            self.view.addSubview((self.playerController?.view)!)
            
            //4.开始播放
            self.playerController?.play()
            
            //5.获取播放结束的时刻
            NSNotificationCenter.defaultCenter().addObserver(self, selector: "endPlay", name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
            
            
        }
        
        
        func endPlay() {
            
            print("结束")
        }
    
    
    }
    
    
    

    相关文章

      网友评论

          本文标题:音频播放AVPlayer

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