音频视频播放可以使用三个类:AVAudioPlayer,AVPlayer和MPMoviePlayerController,其中MPMoviePlayerController在iOS9.0以后被淘汰了,但也可以使用。
AVAudioPlayer
AVAudioPlayer只用于播放音频,使用AVAudioPlayer需要包含AVFoundation库文件,下面的例子UI是通过StoryBoard搭建的,其中分析歌曲信息新建了一个AnalyseMedia类,数据用一个数据模型保存
- ViewController
import UIKit
import AVFoundation
//使用AVAudioPlayer需要包含AVFoundation库文件
class ViewController: UIViewController {
//MARK: - 属性
//注意:播放器对象必须声明称属性,不要使用懒加载
var player:AVAudioPlayer? = nil
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var musicImageView: UIImageView!
//MARK: - 生命周期
override func viewDidLoad() {
super.viewDidLoad()
self.creatPlayer("蓝莲花.mp3")
//添加定时器
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateSlider", userInfo: nil, repeats: true)
}
}
extension ViewController{
func creatPlayer(name:String){
//1.创建音频路径(网络/本地)
let path = NSBundle.mainBundle().pathForResource(name, ofType: nil)
//将本地路径转换成url
let url = NSURL(fileURLWithPath: path!)
//将网络地址转换成url
//let url = NSURL(string: <#T##String#>)
//2.根据url创建播放对象
do{
let tPlayer = try AVAudioPlayer(contentsOfURL: url)
self.player = tPlayer
}catch{
print("音频路径错误")
}
//3.准备播放
self.player?.prepareToPlay()
//4.开始播放
//self.player?.play()
//5.音量(0-1)
self.player?.volume = 1
//6.代理
self.player?.delegate = self
//显示图片
let model = AnalyseMedia.analyseMusic(name)
self.musicImageView.image = model.artwork
}
}
//MARK: - 音频播放和暂停
extension ViewController{
@IBAction func playAction(sender: AnyObject) {
//判断当前播放器是否正在播放音乐
if self.player?.playing == true{
//暂停
//self.player?.stop()//会从断点继续播放
self.player?.pause()//和上面一样
sender.setTitle("播放", forState: .Normal)
}
else{
//播放
self.player?.play()
sender.setTitle("暂停", forState: .Normal)
}
}
}
//MARK: - 音量控制
extension ViewController{
@IBAction func stepAction(sender: UIStepper) {
self.player?.volume = Float(sender.value)
}
}
//MARK: - 播放进度
extension ViewController{
@IBAction func sliderAction(sender: UISlider) {
//拿到当前播放器播放的音乐的总时间
let duration = self.player?.duration
//设置当前播放时间
self.player?.currentTime = duration! * Double(sender.value)
//解决拖动滑条播放卡顿效果(不实时监测)
sender.continuous = false
}
func updateSlider(){
//拿到当前播放时间
let time = self.player?.currentTime
//拿到总时间
let duraction = self.player?.duration
//刷新进度条
self.slider.value = Float(time! / duraction!)
}
}
//MARK: - AVAudioPlayerDelegate协议
extension ViewController:AVAudioPlayerDelegate{
//已经结束播放时自动调用
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
//切换到下一首(实质:重新创建一个对应播放器)
self.creatPlayer("像梦一样自由.mp3")
self.player?.play()
}
}
- AnalyseMedia
import UIKit
import AVFoundation
class AnalyseMedia: NSObject {
//注意:当前方法中不涉及任何类的属性的时候,可以将这个方法声明成类型方法(static),方便直接使用类名来调用
//分析歌曲信息
static func analyseMusic(name:String) -> MediaModel{
//拿到路径
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(name, ofType: nil)!)
//1.创建媒体解析器对象
//参数:需要解析的媒体资源的路径
let asset = AVURLAsset(URL: url)
//2.获取格式
let format = asset.availableMetadataFormats.first
//3.根据指定的格式去获取信息
let infoArray = asset.metadataForFormat(format!)
//4.遍历数组拿到不同的信息
//a.创建模型来获取所有的相关信息
//b.遍历
let model = MediaModel()
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(data: data)
}
}
return model
}
}
- 数据模型
import UIKit
class MediaModel: NSObject {
///演唱者
var artist = ""
///专辑
var albumName = ""
///歌曲名
var title = ""
///插图
var artwork:UIImage? = nil
}
AVPlayer
AVPlayer不仅可以播放音频,还可以播放视频,和AVAudioPlayer一样,使用AVPlayer需要包含AVFoundation库文件。
使用AVPlayer播放音频
下面的例子UI是通过StoryBoard搭建的,其中分析歌曲信息及数据模型和上面的例子一样,这里不再重复放出,里面有关于解析歌词的部分是用前辈的OC第三方库,这里也不放出
- VIewController
import UIKit
import AVFoundation
class ViewController: UIViewController {
//MARK: - 属性
//可以使用懒加载
lazy var player:AVPlayer = {
return self.creatPlayer()
}()
//进度条
@IBOutlet weak var playSlider: UISlider!
//图片
@IBOutlet weak var picImageView: UIImageView!
//歌词解析器
let lyricManager = YTAnalysis()
//歌词
@IBOutlet weak var lyricLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//注册观察者,去观察播放器播放结束的时刻(AVPlayer在播放完成后,消息中心会自动发送播放完成对应的消息)
//播放结束消息名:AVPlayerItemDidPlayToEndTimeNotification
NSNotificationCenter.defaultCenter().addObserver(self, selector: "finishedPlay", name: AVPlayerItemDidPlayToEndTimeNotification, object: nil)
//获取播放器的播放进度
//参数1:时间间隔(每个多长时间获取一次播放进度)
//参数2:执行参数3中的参数的队列
//参数3:每隔参数1时间后需啊哟执行的闭包
//闭包中的参数:当前时间
self.player.addPeriodicTimeObserverForInterval(CMTimeMake(1, 1), queue: dispatch_get_main_queue()) { (cmCurrent) in
//1.拿到总时间
let cmDuration = self.player.currentItem?.duration
//转换成秒时间
let duration = Float((cmDuration?.value)!) / Float((cmDuration?.timescale)!)
//当前时间(秒对应的)
let currant = Float(cmCurrent.value) / Float(cmCurrent.timescale)
//计算百分比
self.playSlider.value = currant / duration
//获取指定时间对应的歌词
let str = self.lyricManager.getLyricWithTime(Double(currant))
self.lyricLabel.text = str
}
}
}
//MARK: - 创建播放器
extension ViewController{
func creatPlayer() -> AVPlayer{
//1.创建播放源
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("蓝莲花.mp3", ofType: nil)!)
let item = AVPlayerItem(URL: url)
//2.创建播放器对象
let player = AVPlayer(playerItem: item)
//3.获取图片信息
self.picImageView.image = AnalyseMedia.analyseMusic("蓝莲花.mp3").artwork
//4.解析歌词
self.lyricManager.analysisLyricWithPath(NSBundle.mainBundle().pathForResource("蓝莲花.lrc", ofType: nil))
return player
}
}
//MARK: - 播放和暂停
extension ViewController{
@IBAction func playAction(sender: UIButton) {
if sender.currentTitle == "播放"{
//1.开始播放
self.player.play()
sender.setTitle("暂停", forState: .Normal)
}
else{
//2.暂停播放
self.player.pause()
sender.setTitle("播放", forState: .Normal)
}
}
}
//MARK: - 控制音量和播放速度
extension ViewController{
//改变音量(0-1)
@IBAction func VolumeAction(sender: UIStepper) {
self.player.volume = Float(sender.value)
}
//改变速度(0.5-2)
@IBAction func rateAction(sender: UIStepper) {
self.player.rate = Float(sender.value)
}
}
//MARK: - 切换播放源
extension ViewController{
func finishedPlay(){
self.changeItem("北京北京")
}
func changeItem(name:String){
//1.创建新的播放源
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource(name, ofType: "mp3")!)
let item = AVPlayerItem(URL: url)
//2.替换播放源
self.player.replaceCurrentItemWithPlayerItem(item)
//3.开始播放
self.player.play()
//4.更新图片
self.picImageView.image = AnalyseMedia.analyseMusic(name + ".mp3").artwork
//5.解析歌词
self.lyricManager.analysisLyricWithPath(NSBundle.mainBundle().pathForResource("\(name).lrc", ofType: nil))
}
}
//MARK: - 进度条
extension ViewController{
@IBAction func sliderAction(sender: UISlider) {
sender.continuous = false
//1.CMTime基础:
//AVPlayer中,总时间 = 总帧数/每一秒播放的帧数
//当前时间 = 当前帧数/每一秒播放的帧数
//将播放器定位到指定的时间
//在AVPlayer中,所有的时间都是以CMTime来确定的
//CMTime中,value属性代表帧数,timeScale代表每一秒播放的帧数。
//一个CMTime变量确定的真正的时间是value/timeScale
//例如创建CMTime,确定一个第10秒(只需要除出的结果是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 currantTime = duration * Double(sender.value)
//c.定位到指定的位置
self.player.seekToTime(CMTimeMake(Int64(currantTime), 1))
}
}
使用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播放视频
使用MPMoviePlayerController时需要导入MediaPlayer,其优点是可以快速创建一个视频播放器,缺点是该播放器不可以定制。
import UIKit
import MediaPlayer
class ViewController: UIViewController {
//属性
var playerContrller: MPMoviePlayerController? = nil
override func viewDidLoad() {
super.viewDidLoad()
//1.创建对象
//创建播放源路径
let url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("MovieTest.mp4", ofType: nil)!)
self.playerContrller = MPMoviePlayerController(contentURL: url)
//2.设置播放器界面的大小
self.playerContrller?.view.frame = self.view.bounds
//3.添加播放器界面
self.view.addSubview((self.playerContrller?.view!)!)
//4.开始播放
self.playerContrller?.play()
//获取结束播放的时刻
NSNotificationCenter.defaultCenter().addObserver(self, selector: "endAction", name: MPMoviePlayerPlaybackDidFinishNotification, object: nil)
}
func endAction(){
print("播放结束")
}
}