如何从Swift中的AVAudioPlayer获取锁定屏幕/控制中心的音频控件 [英] How Do I Get Audio Controls on Lock Screen/Control Center from AVAudioPlayer in Swift
问题描述
iOS开发新手,所以这里。我有一个播放音频的应用程序 - 我正在使用 AVAudioPlayer
在应用程序的资产中按名称加载单个文件。我不想查询用户的库,只查询提供的文件。效果很好,但是,我希望用户能够从锁定屏幕暂停和调整音量。
New to iOS development, so here goes. I have an app that is playing audio - I'm using AVAudioPlayer
to load single files by name in the app's assets. I don't want to query the user's library, only the files provided. Works great, but, I want the user to be able to pause and adjust volume from the lock screen.
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
只是通过阅读其他相关实验帖子。
My use of AVAudioSession
and MPNowPlayingInfoCenter
were just experiments from reading other related posts.
启用后台模式d我的应用程序的plist文件中的音频
Background mode is enabled for audio in my app's plist file
推荐答案
您需要调用beginReceivingRemoteControlEvents(),否则它将无法在实际设备上运行。
You need to invoke beginReceivingRemoteControlEvents() otherwise it will not work on the actual device.
Swift 3.1
UIApplication.shared.beginReceivingRemoteControlEvents()
如果要为MPRemoteCommandCenter指定自定义操作:
If you would like to specify custom actions for the MPRemoteCommandCenter:
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget(self, action:#selector(nextTrackCommandSelector))
这篇关于如何从Swift中的AVAudioPlayer获取锁定屏幕/控制中心的音频控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!