这是iOS开发的新功能.我有一个播放音频的应用程序 - 我正在使用AVAudioPlayer
应用程序资产中的名称加载单个文件.我不想查询用户的库,只查询提供的文件.效果很好,但是,我希望用户能够从锁定屏幕暂停和调整音量.
func initAudioPlayer(file:String, type:String){ let path = NSBundle.mainBundle().pathForResource(file, ofType: type)! let url = NSURL(fileURLWithPath: path) let audioShouldPlay = audioPlaying() do{ try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().setActive(true) let audioPlayer:AVAudioPlayer = try AVAudioPlayer(contentsOfURL: url) audioPlayer.volume = slider.value audioPlayer.numberOfLoops = -1 audioPlayer.prepareToPlay() if(audioShouldPlay){ audioPlayer.play() // let mpic = MPNowPlayingInfoCenter.defaultCenter() // mpic.nowPlayingInfo = [MPMediaItemPropertyTitle:"title", MPMediaItemPropertyArtist:"artist"] } } catch{} }
我使用AVAudioSession
和MPNowPlayingInfoCenter
只是阅读其他相关帖子的实验.
在我的应用程序的plist文件中为音频启用了背景模式
您需要调用beginReceivingRemoteControlEvents(),否则它将无法在实际设备上运行.
Swift 3.1
UIApplication.shared.beginReceivingRemoteControlEvents()
如果要为MPRemoteCommandCenter指定自定义操作:
let commandCenter = MPRemoteCommandCenter.shared() commandCenter.nextTrackCommand.isEnabled = true commandCenter.nextTrackCommand.addTarget(self, action:#selector(nextTrackCommandSelector))