You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyObjC访问MPNowPlayingInfoCenter实现MacOS「正在播放」状态对接

基于PyObjC实现MacOS「正在播放」状态同步方案

调用报错根因

PyObjC对Objective-C框架的方法命名严格遵循原生selector规则,MPNowPlayingInfoCenter的共享实例获取方法在原生接口中为+ defaultCenter,对应PyObjC调用方式为MediaPlayer.MPNowPlayingInfoCenter.defaultCenter(),你使用的default()不是正确的方法名,这是调用报错的核心原因。

完整实现步骤

  • 首先安装对应框架绑定:
    执行命令:pip install pyobjc-framework-MediaPlayer
  • 导入依赖模块:
from Foundation import NSDictionary, NSString, NSNumber
from MediaPlayer import (
    MPNowPlayingInfoCenter,
    MPNowPlayingInfoPropertyElapsedPlaybackTime,
    MPNowPlayingInfoPropertyPlaybackRate,
    MPMediaItemPropertyTitle,
    MPMediaItemPropertyArtist,
    MPMediaItemPropertyPlaybackDuration,
    MPMediaItemPropertyArtwork,
    MPMediaItemArtwork
)
from AppKit import NSImage
  • 获取「正在播放」中心共享实例:
now_playing_center = MPNowPlayingInfoCenter.defaultCenter()
  • 构造媒体信息字典:
# 基础媒体信息
playback_info = NSDictionary.dictionaryWithObjects_forKeys_(
    [
        NSString.stringWithString_("示例歌曲"),
        NSString.stringWithString_("示例艺术家"),
        NSNumber.numberWithDouble_(180.0),  # 总播放时长,单位:秒
        NSNumber.numberWithDouble_(25.5),  # 当前已播放时长,单位:秒
        NSNumber.numberWithFloat_(1.0),  # 播放速率,1为正常播放,0为暂停
    ],
    [
        MPMediaItemPropertyTitle,
        MPMediaItemPropertyArtist,
        MPMediaItemPropertyPlaybackDuration,
        MPNowPlayingInfoPropertyElapsedPlaybackTime,
        MPNowPlayingInfoPropertyPlaybackRate,
    ]
)

# 可选:添加专辑封面
cover = NSImage.alloc().initWithContentsOfFile_("./album_cover.jpg")
artwork = MPMediaItemArtwork.alloc().initWithImage_(cover)
playback_info[MPMediaItemPropertyArtwork] = artwork
  • 同步信息到系统:
now_playing_center.setNowPlayingInfo_(playback_info)

注意事项

  • 播放状态变更(切歌、暂停/播放、进度跳转)时需要主动更新nowPlayingInfo字段,系统不会自动同步播放器内部状态
  • 暂停播放时必须将MPNowPlayingInfoPropertyPlaybackRate设置为0,否则系统状态栏的播放进度会持续自动递增
  • 若应用需要在后台运行时保持「正在播放」状态显示,需要先申请音频后台播放权限

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 01:45:03