好几天米撸了,今天撸篇..音乐后台播放操作及显示封面
按步骤,今天的主题主要是实现后台播放及显示,其他播放音乐步骤略过...
锁屏 上拉Info.plist第一步:Info.plist
方便大家复制:上代码
Required background modes | App plays audio or streams audio/video using AirPlay
第二步:AppDelegate.swift
/**注意:记得先在头部写上 import AVFoundation */
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// 注册后台播放
let session = AVAudioSession.sharedInstance()
do {
try session.setActive(true)
try session.setCategory(AVAudioSessionCategoryPlayback)
} catch {
print(error)
}
return true
}
第三步:ViewController.swift
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
//1.告诉系统接受远程响应事件,并注册成为第一响应者
UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
self.becomeFirstResponder()
}
override func viewWillDisappear(animated: Bool) {
UIApplication.sharedApplication().endReceivingRemoteControlEvents()
self.resignFirstResponder()
}
override func canBecomeFirstResponder() -> Bool {
return true
}
/*
* 加载音乐文件略 ,定时器定时更新后台信息略....
* audioPlayer = try! AVAudioPlayer... //加载
* audioPlayer.paly() //播放 audioPlayer.stop() //暂停
* audioPlayer.currentTime //可以更改播放进度
* 以后有空再来一波
*/
}
// MARK: - 设置后台播放显示信息
extension ViewController {
func setBackground() {
//大标题 - 小标题 - 歌曲总时长 - 歌曲当前播放时长 - 封面
let settings = [MPMediaItemPropertyTitle: "大标题",
MPMediaItemPropertyArtist: "小标题",
MPMediaItemPropertyPlaybackDuration: "\(audioPlayer.duration)",
MPNowPlayingInfoPropertyElapsedPlaybackTime: "\(audioPlayer.currentTime)",
MPMediaItemPropertyArtwork: MPMediaItemArtwork(image: UIImage(named: " cover")!)]
MPNowPlayingInfoCenter.defaultCenter().setValue(settings, forKey: "nowPlayingInfo")
}
}
// MARK: - 后台操作
extension ViewController {
override func remoteControlReceivedWithEvent(event: UIEvent?) {
if event?.type == UIEventType.RemoteControl {
switch event!.subtype {
case .RemoteControlTogglePlayPause:
print("暂停/播放")
case .RemoteControlPreviousTrack: // ## <- ##
print("上一首")
case .RemoteControlNextTrack: // ## -> ##
print("下一首")
case .RemoteControlPlay: // ## > ##
print(">")
case .RemoteControlPause: // ## || ##
print("||")
default:
break
}
}
}
}
网友评论