Audio playback lock screen control not displaying
我正在尝试在锁定屏幕上显示音频控件,但问题是音频控件在锁定屏幕上不显示任何内容。我已经启用了后台模式,并且音频在后台播放。
在应用委托类中,当我的应用启动时,我设置了我的音频会话
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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 函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 中的所有问题,但没有运气。
问题是您的
要让您的
您拥有的背景音频是一种派生要求,因为 lockscreen=>background=>播放音频需要背景音频,所以我应该将其添加到另一个答案中。
如果问题是锁屏控件未启用/没有响应,那么请尝试添加
附言你的
1 | nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = CMTimeGetSeconds(audioplayerItem.currentTime) |
这样做(这是swift 3):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | override func viewDidLoad() { super.viewDidLoad() UIApplication.shared.beginReceivingRemoteControlEvents() let commandCenter = MPRemoteCommandCenter.shared() commandCenter.pauseCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in //Update your button here for the pause command return .success } commandCenter.playCommand.addTarget { (event) -> MPRemoteCommandHandlerStatus in //Update your button here for the play command return .success } } |
This answer found HERE