如何在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{} }
我使用AVAudioSession
和MPNowPlayingInfoCenter
只是通过阅读其他相关文章的实验。
后台模式在我的应用程序的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的文档中所述 。
- 在应用程序中创build一个UISlider进度条和计时器(如iPod播放器)
- 在iOS中同时录制和播放audio
- 尽pipeprepareToPlay()在Swift中AVAudioPlayer产生滞后
- iOS – AVAudioPlayer在后台不会继续播放下一首歌曲
- 如何告诉MPNowPlayingInfoCenter是否正在播放或暂停音乐?
- iPhone:以编程方式访问语音备忘录
- 如何在audioPlayerDidFinishPlaying方法中多次播放()
- 在后台播放AVAudioPlayer的一个实例
- MPMediaItem不使用MPMediaItemPropertyAssetURL在AVAudioPlayer中播放