You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

如何无需遍历所有窗口精准获取目标窗口名称?Spotify播放歌曲信息提取方案优化咨询

Hey there! That pygetwindow approach you've got is definitely prone to false positives—scanning every window title for a hyphen is way too broad, since tons of apps use that in their titles. Let's fix this with methods that target Spotify directly, so you never get misreads again.

Option 1: Pinpoint Spotify's Window Directly (Quick Fix)

Instead of looping through every open window, we can ask pygetwindow to only fetch windows related to Spotify. This cuts out all the noise right away.

Here's the refined code:

import pygetwindow as gw
import time
import os

while True:
    # Grab only windows with "Spotify" in the title
    spotify_windows = gw.getWindowsWithTitle("Spotify")
    if spotify_windows:
        spotify_title = spotify_windows[0].title
        # Spotify's playing format is always "Artist - Song Title"
        if " - " in spotify_title and spotify_title != "Spotify":
            # Split once to handle artists with hyphens in their name
            artist, song = spotify_title.split(" - ", 1)
            print(f"Now playing: {artist.strip()} - {song.strip()}")
        else:
            print("Spotify is open but not playing a song.")
    else:
        print("Spotify isn't running.")
    
    time.sleep(1)
    os.system('cls' if os.name == 'nt' else 'clear')

This works because we're only looking at Spotify's windows, so no more accidental matches from Firefox, Steam, or other apps.

Option 2: Use Spotify's Official API (Most Reliable)

If you want rock-solid accuracy (and access to extra details like album art, play progress, or playlist info), the official Spotify API is the way to go. You'll need a free developer account first:

  1. Head to the Spotify Developer Dashboard and create a new app
  2. Grab your Client ID and Client Secret
  3. Set a redirect URI (we'll use http://localhost:8888/callback for this example)

Then install the spotipy library:

pip install spotipy

Here's the code:

import spotipy
from spotipy.oauth2 import SpotifyOAuth
import time
import os

# Replace these with your own developer credentials
SPOTIPY_CLIENT_ID = "your_client_id_here"
SPOTIPY_CLIENT_SECRET = "your_client_secret_here"
SPOTIPY_REDIRECT_URI = "http://localhost:8888/callback"

# Authenticate (you'll log in once via browser)
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
    client_id=SPOTIPY_CLIENT_ID,
    client_secret=SPOTIPY_CLIENT_SECRET,
    redirect_uri=SPOTIPY_REDIRECT_URI,
    scope="user-read-currently-playing"
))

while True:
    current_track = sp.current_user_playing_track()
    if current_track:
        artist = current_track['item']['artists'][0]['name']
        song_title = current_track['item']['name']
        print(f"Now playing: {artist} - {song_title}")
        # Bonus: Uncomment to get album name
        # album = current_track['item']['album']['name']
        # print(f"Album: {album}")
    else:
        print("No song is currently playing on Spotify.")
    
    time.sleep(1)
    os.system('cls' if os.name == 'nt' else 'clear')

This method is 100% accurate because we're pulling data directly from Spotify, not guessing based on window titles.

Option 3: Windows-Only No-API Approach (Class Name Targeting)

If you don't want to mess with APIs, you can use Windows' native window classes to confirm you're targeting the real Spotify window (in case the title ever gets wonky). We'll use pywin32 for this:

First install the library:

pip install pywin32

Then the code:

import win32gui
import time
import os

def get_spotify_title():
    # Callback function to find Spotify's main window
    def window_callback(handle, titles):
        window_title = win32gui.GetWindowText(handle)
        if window_title and "Spotify" in window_title:
            # Spotify's main window uses this class name
            if win32gui.GetClassName(handle) == "Chrome_WidgetWin_0":
                titles.append(window_title)
        return True
    
    spotify_titles = []
    win32gui.EnumWindows(window_callback, spotify_titles)
    return spotify_titles[0] if spotify_titles else None

while True:
    spotify_title = get_spotify_title()
    if spotify_title:
        if " - " in spotify_title and spotify_title != "Spotify":
            artist, song = spotify_title.split(" - ", 1)
            print(f"Now playing: {artist.strip()} - {song.strip()}")
        else:
            print("Spotify is open but not playing.")
    else:
        print("Spotify isn't running.")
    
    time.sleep(1)
    os.system('cls' if os.name == 'nt' else 'clear')

This uses Spotify's unique window class name to avoid any mix-ups, even if other windows have "Spotify" in their title.


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

火山引擎 最新活动