Swift 音频播放锁定屏幕控件未显示
我尝试在锁屏上显示音频控件,但问题是音频控件在锁屏上不显示任何内容。我已经启用了后台模式,音频在后台播放 应用程序内委托类,当我的应用程序启动时,我设置了音频会话Swift 音频播放锁定屏幕控件未显示,swift,avplayer,avaudiosession,Swift,Avplayer,Avaudiosession,我尝试在锁屏上显示音频控件,但问题是音频控件在锁屏上不显示任何内容。我已经启用了后台模式,音频在后台播放 应用程序内委托类,当我的应用程序启动时,我设置了音频会话 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { setupAudioSession()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
setupAudioSession()
UIApplication.shared.beginReceivingRemoteControlEvents()
return true
}
func setupAudioSession(){
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: [])
self.becomeFirstResponder()
do {
try AVAudioSession.sharedInstance().setActive(true)
print("AVAudioSession is Active")
} catch let error as NSError {
print(error.localizedDescription)
}
} catch let error as NSError {
print(error.localizedDescription)
}
}
在我的主控制器中,我在播放音频后调用setupLockScreen功能
func setupLockScreen(){
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.playCommand.isEnabled = true
commandCenter.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in
if self.player?.rate == 0.0 {
self.player?.play()
return .success
}
return .commandFailed
}
var nowPlayingInfo = [String : Any]()
nowPlayingInfo[MPMediaItemPropertyTitle] = "My Song"
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = audioplayerItem.duration.seconds
nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = audioplayerItem.asset.duration.seconds
nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player?.rate
MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}
我读了很多文章,在Stack Overflow中查找了所有问题,但没有运气。这样做(这是swift 3):
这个答案找到了
问题是您现在播放的信息未显示在锁屏上,还是您添加的控件没有响应 要使您的
nowPlayingInfo
显示在锁屏上,您需要做几件事。一个是有一个不可混合的音频会话(您已经使用了AVAudioSessionCategoryPlayback
),另一个是正在播放音频或最近才停止播放音频。你的应用程序真的在播放音频吗
背景音频,这是一种派生需求,因为播放音频需要lockscreen=>Background=>Background音频,所以我应该将其添加到另一个答案中
如果问题是锁屏控件未启用/响应,请尝试添加pauseCommand
。playCommand
/pauseCommand
对似乎是接收锁屏/外部播放器命令的最低要求
p、 s.您的mpNowPlayingInFoPropertyLapsedPlaybackTime
看起来有误。难道不是吗
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = CMTimeGetSeconds(audioplayerItem.currentTime)
这和他现在做的有什么不同?加上它只是重复另一个答案的代码;不要那样做。一个评论就足够了。谢谢你。“非混音音频会话”为我解决了这个问题。当我在app delegate中将此作为音频会话的选项时,控件没有出现。
nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = CMTimeGetSeconds(audioplayerItem.currentTime)