AVPlayerViewController播放远程MP4时Now Playing栏信息不显示求助
问题原因与解决方案
核心原因
AVPlayerViewController默认会自动接管MPNowPlayingInfoCenter的更新,它会优先读取视频文件的内嵌元数据(或URL对应的文件名)覆盖你手动设置的自定义信息,导致你写的标题、艺术家信息显示不出来。- 当你设置
updatesNowPlayingInfoCenter = false关闭自动更新后,系统同时停止了对远程播放控件(锁屏/控制中心的播放、暂停按钮)的事件处理,所以控件失效。
修复步骤
要同时实现自定义信息显示和播放控件正常工作,需要手动管理MPNowPlayingInfoCenter并处理远程控制事件:
1. 修改viewDidLoad配置
在初始化playerViewController后添加以下配置:
playerViewController.updatesNowPlayingInfoCenter = false // 注册远程控制事件 UIApplication.shared.beginReceivingRemoteControlEvents() // 监听播放器状态变化,实时更新NowPlaying信息 player.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(1, preferredTimescale: 1), queue: .main) { [weak self] time in self?.updateNowPlayingInfo() }
2. 完善NowPlaying信息更新逻辑
把原来的setupNowPlaying改成updateNowPlayingInfo,补充播放状态、进度等必要信息,让控制中心控件能正常响应:
func updateNowPlayingInfo() { guard let currentItem = player.currentItem else { return } var nowPlayingInfo = [String: Any]() // 自定义信息 nowPlayingInfo[MPMediaItemPropertyTitle] = "title example" nowPlayingInfo[MPMediaItemPropertyArtist] = "artist example" // 播放状态与进度(必须添加,否则控制中心控件失效) nowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = CMTimeGetSeconds(currentItem.currentTime()) nowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = CMTimeGetSeconds(currentItem.duration) nowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = player.rate MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo }
3. 处理远程控制事件
在PlayerViewController中添加远程控制事件的处理方法:
override func remoteControlReceived(with event: UIEvent?) { guard let eventType = event?.subtype else { return } switch eventType { case .remoteControlPlay: player.play() case .remoteControlPause: player.pause() // 可选:处理快进、快退等其他事件 case .remoteControlForward: player.seek(to: player.currentTime() + CMTimeMakeWithSeconds(10, preferredTimescale: 1)) case .remoteControlRewind: player.seek(to: player.currentTime() - CMTimeMakeWithSeconds(10, preferredTimescale: 1)) default: break } // 更新播放状态到NowPlaying中心 updateNowPlayingInfo() }
4. 清理资源
在deinit中停止接收远程控制事件:
deinit { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem) player?.pause() // 停止接收远程控制事件 UIApplication.shared.endReceivingRemoteControlEvents() }
额外注意点
- 确保你的App已经开启了后台音频权限(在
Info.plist中添加UIBackgroundModes数组,包含audio项),否则后台播放和控制中心功能可能异常。 - 如果视频文件本身有内嵌元数据,你可以选择读取并合并到自定义信息中,或者直接用自定义信息完全覆盖。
内容的提问来源于stack exchange,提问作者Noise182
相关产品推荐
相关产品推荐

