如何在Swift中从AVAudioPlayer获取locking屏幕/控制中心的audio控制

新的iOS开发,所以这里。 我有一个应用程序正在播放audio – 我正在使用AVAudioPlayer按名称加载应用程序的资产中的单个文件。 我不想查询用户的库,只有提供的文件。 很好,但是,我希望用户能够从locking屏幕暂停和调整音量。

 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{} } 

我使用AVAudioSessionMPNowPlayingInfoCenter只是通过阅读其他相关文章的实验。

后台模式在我的应用程序的plist文件中为audio启用

你需要调用beginReceivingRemoteControlEvents(),否则它将不能在实际的设备上工作。

Swift 3.1

 UIApplication.shared.beginReceivingRemoteControlEvents() 

如果您想为MPRemoteCommandCenter指定自定义操作:

 let commandCenter = MPRemoteCommandCenter.shared() commandCenter.nextTrackCommand.isEnabled = true commandCenter.nextTrackCommand.addTarget(self, action:#selector(nextTrackCommandSelector)) 
 func myplayer(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{} } 

锁屏上已经有audio控制(“遥控”界面)。 如果您希望他们控制应用程序的audio,则需要将您的应用程序设置为远程控制目标 ,如Apple的文档中所述 。