开启Background Modes -> Audio, airPlay
//告诉系统接受远程响应事件,并注册成为第一响应者
UIApplication.shared.beginReceivingRemoteControlEvents()
self.becomeFirstResponder()
let mpic = MPNowPlayingInfoCenter.default()
//专辑封面
let mySize = CGSize(width:400, height:400)
let albumArt = MPMediaItemArtwork(boundsSize:mySize) { szin
return UIImage(named:"cover")!
}
//获取进度
letpostion = Double(self.playbackSlider!.value)
letduration = Double(self.playbackSlider!.maximumValue)
mpic.nowPlayingInfo = [MPMediaItemPropertyTitle: "我是歌曲标题",
MPMediaItemPropertyArtist:"hangge.com",
MPMediaItemPropertyArtwork: albumArt,
MPNowPlayingInfoPropertyElapsedPlaybackTime: postion,
MPMediaItemPropertyPlaybackDuration: duration,
MPNowPlayingInfoPropertyPlaybackRate: playbackState]
//后台操作
override func remoteControlReceived(with event:UIEvent?) {
guard let event = event else{
print("no event\n")
return
}
if event.type == UIEventType.remoteControl {
switch event.subtype{
case .remoteControlTogglePlayPause:
print("暂停/播放")
case .remoteControlPreviousTrack:
print("上一首")
case .remoteControlNextTrack:
print("下一首")
case .remoteControlPlay:
print("播放")
player!.play()
case .remoteControlPause:
print("暂停")
player!.pause()
//后台播放显示信息进度停止
setInfoCenterCredentials(playbackState:0)
default:
break
}
}
}