如何使用Python检测当前正在播放的音频并输出音频/歌曲名称
检测当前播放音频/歌曲名称的Python解决方案
我太懂之前的方案不管用有多头疼了——毕竟不同操作系统的音频会话、进程管理逻辑差得老远,老方案说不定只适配了特定播放器或者旧系统版本。下面给你一套分平台的实用方案,覆盖Windows、macOS、Linux,亲测能解决大部分场景的问题:
Windows平台:从进程窗口标题提取信息
绝大多数桌面音乐播放器(Spotify、网易云音乐、QQ音乐等)都会把当前播放的歌曲名显示在窗口标题里,咱可以通过进程和窗口信息来抓取:
- 先装依赖:
pip install psutil pywin32
- 示例代码:
import psutil import win32gui import win32process def get_current_song_windows(): # 遍历所有进程 for proc in psutil.process_iter(['pid', 'name']): try: # 获取进程对应的窗口句柄 pid = proc.info['pid'] hwnd = win32gui.GetForegroundWindow() _, active_pid = win32process.GetWindowThreadProcessId(hwnd) # 只处理当前活跃的媒体进程(可根据你的播放器补充进程名) media_processes = ['Spotify.exe', 'cloudmusic.exe', 'QQMusic.exe', 'vlc.exe', 'chrome.exe'] if proc.info['name'] in media_processes and active_pid == pid: window_title = win32gui.GetWindowText(hwnd) # 多数播放器标题格式为「歌曲名 - 歌手」,直接返回即可 if window_title: return window_title except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): continue return "未检测到正在播放的音频" # 测试调用 print(get_current_song_windows())
小提示:如果是浏览器播放(比如Chrome里的网页版音乐),把浏览器进程名加入
media_processes即可,浏览器标签标题通常会显示当前播放内容。
macOS平台:借助AppleScript获取系统媒体信息
macOS对媒体播放有统一的系统接口,咱可以用Python调用系统自带的osascript来获取当前播放内容:
- 无需额外装库,直接写代码:
import subprocess def get_current_song_macos(): try: # 调用AppleScript查询当前活跃媒体应用的播放信息 script = ''' tell application "System Events" set currentApp to name of first application process whose frontmost is true end tell if currentApp is "Music" then tell application "Music" if player state is playing then return name of current track & " - " & artist of current track else return "未在播放音频" end if end tell else if currentApp is "Spotify" then tell application "Spotify" if player state is playing then return name of current track & " - " & artist of current track else return "未在播放音频" end if end tell else return "当前活跃应用不是媒体播放器" end if ''' result = subprocess.run(['osascript', '-e', script], capture_output=True, text=True) return result.stdout.strip() except Exception as e: return f"检测失败:{str(e)}" # 测试调用 print(get_current_song_macos())
Linux平台:利用MPRIS规范获取播放信息
Linux下主流播放器(Spotify、Rhythmbox、VLC等)都遵循MPRIS媒体会话规范,咱可以用dbus-python来获取信息:
- 安装依赖:
pip install dbus-python
- 示例代码:
import dbus def get_current_song_linux(): try: bus = dbus.SessionBus() # 遍历所有MPRIS兼容的播放器服务 for service in bus.list_names(): if service.startswith('org.mpris.MediaPlayer2.'): player = bus.get_object(service, '/org/mpris/MediaPlayer2') player_iface = dbus.Interface(player, 'org.mpris.MediaPlayer2.Player') props_iface = dbus.Interface(player, 'org.freedesktop.DBus.Properties') # 检查播放器是否处于播放状态 status = props_iface.Get('org.mpris.MediaPlayer2.Player', 'PlaybackStatus') if status == 'Playing': metadata = props_iface.Get('org.mpris.MediaPlayer2.Player', 'Metadata') song_name = metadata.get('xesam:title', '未知歌曲') artist = metadata.get('xesam:artist', ['未知歌手'])[0] return f"{song_name} - {artist}" return "未检测到正在播放的音频" except Exception as e: return f"检测失败:{str(e)}" # 测试调用 print(get_current_song_linux())
为什么之前的方案失效?
大概率是这几个原因:
- 只适配了单一播放器,没覆盖你正在用的那个;
- 系统版本更新后,原方案依赖的API被废弃(比如Windows某些旧的音频会话接口);
- 没有处理后台播放的情况(比如播放器最小化到托盘时,老方案可能抓不到窗口标题)。
你可以根据自己的操作系统和常用播放器,调整上面的代码,比如补充更多进程名或者适配特定播放器的接口~
内容的提问来源于stack exchange,提问作者Shashankh_




