You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

iOS 11锁屏及控制中心音频播放器远程控件不显示求助

解决锁屏/控制中心远程控件不显示的问题

根据你描述的配置情况,我整理了几个关键排查点,你可以逐一验证来解决控件不显示的问题:

1. 确保MPNowPlayingInfoCenter信息完整且时机正确

系统需要感知到有效的播放元数据才会加载远程控件,你要确保在音频开始播放之后,给nowPlayingInfo设置足够的核心字段,比如标题、歌手这类基础信息,示例代码:

func updateNowPlayingInfo() {
    guard let currentItem = player.currentItem else { return }
    var nowPlayingInfo = [String: Any]()
    nowPlayingInfo[MPMediaItemPropertyTitle] = "当前歌曲名"
    nowPlayingInfo[MPMediaItemPropertyArtist] = "歌手名称"
    nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = player.currentTime().seconds
    nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = currentItem.duration.seconds
    nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate
    MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo
}

记得在播放、暂停、切换曲目时都调用这个方法更新信息。

2. 确认MPRemoteCommandCenter命令已启用并正确处理

你已经添加了命令目标,但要确保每个命令都开启了启用状态,并且处理方法返回正确的状态:

let commandCenter = MPRemoteCommandCenter.shared()
// 播放命令
commandCenter.playCommand.isEnabled = true
commandCenter.playCommand.addTarget(self, action: #selector(playRemoteHandler(_:)))
// 暂停命令
commandCenter.pauseCommand.isEnabled = true
commandCenter.pauseCommand.addTarget(self, action: #selector(pauseRemoteHandler(_:)))
// 上/下一曲同理

处理方法要返回.success告知系统命令已处理:

@objc func playRemoteHandler(_ command: MPRemoteCommand) -> MPRemoteCommandHandlerStatus {
    player.play()
    updateNowPlayingInfo()
    return .success
}

3. 优化AVAudioSession的配置时机

虽然你在didFinishLaunchingWithOptions里配置了会话,但如果播放器是延迟初始化的,建议在播放器准备播放前再次确认会话状态,避免会话被其他操作覆盖:

func preparePlayer() {
    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch {
        print("音频会话激活失败: \(error)")
    }
    // 初始化播放器逻辑...
}

同时确保没有其他地方误将会话类别改成AVAudioSessionCategoryAmbient(这个类别不支持后台播放和远程控件)。

4. 移除不必要的beginReceivingRemoteControlEvents

官方文档明确说明,使用MPRemoteCommandCenter时不需要调用application.beginReceivingRemoteControlEvents(),这行代码反而可能造成冲突,建议直接移除。

5. 测试时的关键注意事项

  • 不要用模拟器测试:模拟器的锁屏/控制中心经常无法正确加载音频控件,一定要用真实iOS设备测试;
  • 播放后等待几秒:系统加载远程控件可能有延迟,播放音频后手动锁屏或下拉控制中心,稍等片刻再查看;
  • 检查控制台日志:如果还是不行,查看Xcode控制台有没有音频会话激活失败、命令注册失败的报错信息,这些能帮你快速定位问题。

内容的提问来源于stack exchange,提问作者Orxan Kerimli

火山引擎 最新活动