watchOS 6下如何将应用音频信息同步至Now Playing界面?
我之前也踩过类似的坑,给你整理几个关键的排查点和补充方案,应该能帮你搞定Apple Watch Now Playing的显示问题:
你已经尝试过这个组件,但大概率是某个细节没做到位:
AVAudioSession必须配置到位
别只设置类别就完事,要确保激活成功,且类别选对。比如必须用.playback类别,这个是系统识别“可被Now Playing追踪”的播放类型。代码示例:do { let session = AVAudioSession.sharedInstance() try session.setCategory(.playback, mode: .default) try session.setActive(true, options: .notifyOthersOnDeactivation) } catch { print("Audio Session配置失败: \(error)") }另外别忘了在Info.plist里添加
audio后台模式权限(UIBackgroundModes数组里加audio),否则后台播放时系统会切断你的播放会话。NowPlayingInfo字典要完整且实时更新
不能只在播放开始时设置一次,要在播放状态变化(开始/暂停)、曲目切换、进度更新时都同步更新字典。尤其要注意MPNowPlayingInfoPropertyPlaybackRate这个字段——0代表暂停,1代表播放,Watch上的控制按钮完全靠这个字段识别状态。示例代码:func updateNowPlayingInfo() { guard let currentItem = player.currentItem else { return } let nowPlayingInfo: [String: Any] = [ MPMediaItemPropertyTitle: "当前曲目名称", MPMediaItemPropertyArtist: "艺术家名字", MPNowPlayingInfoPropertyElapsedPlaybackTime: player.currentTime().seconds, MPMediaItemPropertyPlaybackDuration: currentItem.duration.seconds, MPNowPlayingInfoPropertyPlaybackRate: player.rate ] MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo }必须注册远程控制事件
系统需要确认你的App能响应远程控制(比如Watch上的播放/暂停按钮),才会把播放信息推送到Watch。在App启动时或者播放初始化时添加:UIApplication.shared.beginReceivingRemoteControlEvents()还要实现远程控制事件的处理方法(比如在AppDelegate或者你的播放管理类里):
override func remoteControlReceived(with event: UIEvent?) { guard let event = event, event.type == .remoteControl else { return } switch event.subtype { case .remoteControlPlay: player.play() case .remoteControlPause: player.pause() // 其他需要的控制事件,比如上一曲/下一曲 default: break } // 处理完事件后更新NowPlayingInfo updateNowPlayingInfo() }
手动触发Now Playing刷新
有时候系统会延迟更新,你可以在设置完nowPlayingInfo后发送一个通知强制刷新:NotificationCenter.default.post(name: NSNotification.Name.MPNowPlayingInfoCenterDidUpdate, object: nil)检查Watch的配对与权限
确保iPhone和Watch已正常配对,且你的App已安装到Watch(如果是独立App);如果是iPhone端的App,要保证App在后台运行时没有被系统杀死。另外,Watch的Now Playing需要访问媒体信息权限,确认iPhone上你的App权限设置里没有禁止相关访问。利用AVPlayerItem的元数据自动更新
如果你的音频流带有元数据(比如HLS流的ID3标签),可以监听AVPlayerItemMetadataOutput来自动提取曲目信息,实时更新到NowPlayingInfoCenter,这样更准确也更省心。
大部分情况下,都是漏了上面某一个环节——比如没注册远程控制事件,或者AudioSession激活失败。把这些点逐一排查,应该就能在Watch的Now Playing里看到你的播放信息了。
内容的提问来源于stack exchange,提问作者leoMehlig

