如何用Python获取Windows系统当前播放的媒体标题?
Hey there! Getting the currently playing media title on Windows with Python is totally doable, and I’ve got a couple of solid approaches for you depending on your needs. Let’s dive in.
Method 1: Window Title Scraping (Simple & Quick)
This method works for most common media players that update their window title with the current track/title. It’s super straightforward, though it won’t work if the player is minimized or playing in the background without updating the window title.
Step 1: Install Required Library
First, install the pywin32 package to interact with Windows APIs:
pip install pywin32
Step 2: Code Implementation
import win32gui def get_foreground_media_title(): # Get the title of the currently active window window_handle = win32gui.GetForegroundWindow() return win32gui.GetWindowText(window_handle) def get_all_player_titles(player_name="Spotify"): # Scan all open windows for a specific player's title titles = [] def window_callback(handle, extra_list): title = win32gui.GetWindowText(handle) if title and player_name in title: extra_list.append(title) win32gui.EnumWindows(window_callback, titles) return titles[0] if titles else f"No {player_name} window found" # Example usage print("Foreground window title:", get_foreground_media_title()) print("Spotify current track:", get_all_player_titles("Spotify"))
Pros & Cons
- Pros:
- Minimal code, quick to implement.
- Easy to tweak for targeting specific media players.
- Cons:
- Relies on window titles (many players don’t update this when minimized or playing in the background).
- Title formatting varies widely between apps, making parsing tricky.
Method 2: Windows Media Session API (Reliable & Background-Friendly)
This method uses Windows’ built-in Media Session API, which lets you fetch media info directly from the system—even if the player is running in the background. It works with all modern apps that support this API (Spotify, Edge, YouTube, Windows Media Player, etc.).
Step 1: Install Required Library
Same as above, install pywin32:
pip install pywin32
Step 2: Code Implementation
import win32com.client import pythoncom class MediaFetcher: def __init__(self): # Initialize COM interface for media sessions self.dev_enumerator = win32com.client.Dispatch("MMDeviceEnumerator") self.default_endpoint = self.dev_enumerator.GetDefaultAudioEndpoint(0, 1) # Render, Multimedia self.session_manager = self.default_endpoint.Activate( "{77AA99A0-1BD6-484F-8BC7-2C654C9A9B6F}", 0, None ).QueryInterface(pythoncom.IID_IDispatch) def get_current_media(self): # Iterate through active media sessions to find playing content for session in self.session_manager.Sessions: try: media_props = session.QueryInterface("{657804FA-D6AD-4496-8A60-352752AF4F89}") props = media_props.GetAllProperties() title = props.get("Title", "Unknown Title") artist = props.get("Artist", "Unknown Artist") if title != "Unknown Title": return f"{artist} - {title}" except Exception: # Skip sessions that don't expose media properties continue return "No media is currently playing" if __name__ == "__main__": # Initialize COM (required for Windows API calls) pythoncom.CoInitialize() fetcher = MediaFetcher() print("Now playing:", fetcher.get_current_media()) pythoncom.CoUninitialize()
Pros & Cons
- Pros:
- Works even when media is playing in the background.
- Supports nearly all modern media apps (Spotify, Edge, YouTube, etc.).
- Returns structured data (title, artist) instead of raw window text.
- Cons:
- Code is more complex due to Windows COM interface interactions.
- Older or non-standard media players might not support the Media Session API.
Quick Notes
- If you run into permission issues, try launching your Python script with admin privileges (though this is rarely needed).
- For
pywin32installation errors, make sure you’re using a Python version compatible with the package (check PyPI for supported versions).
内容的提问来源于stack exchange,提问作者roil

