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

使用Spotipy获取当前播放列表及曲目信息遇阻

解决Spotipy遍历当前播放列表的两个问题

问题1:查看current_user_playing_track()返回格式

直接JSON美化打印报错,大概率是当前无正在播放曲目导致current_track为None,或是未正确处理返回结果。先判断播放状态,再用json.dumps格式化输出即可:

import json

current_track = sp.current_user_playing_track()
if current_track:
    print(json.dumps(current_track, indent=2))
else:
    print("当前没有正在播放的曲目")

执行后就能看到完整返回结构,包含item(曲目详情)、context(播放上下文,如播放列表、电台)等核心字段。

问题2:获取当前播放曲目所属播放列表

current_user_playing_track()的context字段存储播放来源信息:若从播放列表播放,context["type"]值为"playlist",同时包含播放列表的id或uri。通过该ID调用sp.playlist()即可获取完整播放列表数据:

current_track = sp.current_user_playing_track()
if current_track and current_track.get("context"):
    context_type = current_track["context"]["type"]
    if context_type == "playlist":
        playlist_id = current_track["context"]["id"]
        current_playlist = sp.playlist(playlist_id)
        print(f"当前播放列表:{current_playlist['name']}")
        print(f"曲目总数:{current_playlist['tracks']['total']}")
        # 遍历播放列表曲目
        tracks = current_playlist["tracks"]["items"]
        for idx, track_item in enumerate(tracks, 1):
            track = track_item["track"]
            print(f"{idx}. {track['name']} - {track['artists'][0]['name']}")
    else:
        print(f"当前播放来源不是播放列表,类型为:{context_type}")
else:
    print("当前无正在播放曲目或无法获取播放上下文")

完整修改后的代码

import spotipy
import spotipy.util as util
import json

MY_ID   = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
SECRET = "000000000000000000000000000000000"

username = "xxxxxxxxxxxxxxxxxxx"
# 需添加playlist-read-private权限,才能获取私人播放列表详情
scope    = "user-read-currently-playing playlist-read-private"
# 回调地址需与Spotify开发者后台设置一致,示例为本地常用地址
redirect_uri = "http://localhost:8888/callback"

token = util.prompt_for_user_token(username, scope, client_id=MY_ID, client_secret=SECRET, redirect_uri=redirect_uri)

if token:
    sp = spotipy.Spotify(auth=token)
    
    # 查看当前播放曲目完整返回结构
    current_track = sp.current_user_playing_track()
    if current_track:
        print("当前播放曲目返回结构:")
        print(json.dumps(current_track, indent=2))
        
        # 获取并遍历当前播放列表
        if current_track.get("context"):
            context_type = current_track["context"]["type"]
            if context_type == "playlist":
                playlist_id = current_track["context"]["id"]
                current_playlist = sp.playlist(playlist_id)
                print("\n当前播放列表信息:")
                print(f"名称:{current_playlist['name']}")
                print(f"所有者:{current_playlist['owner']['display_name']}")
                
                print("\n播放列表曲目:")
                tracks = current_playlist["tracks"]["items"]
                for idx, track_item in enumerate(tracks, 1):
                    track = track_item["track"]
                    print(f"{idx}. {track['name']} - {track['artists'][0]['name']}")
            else:
                print(f"\n当前非播放列表播放,来源类型:{context_type}")
        else:
            print("\n无法获取播放上下文(可能为单曲或本地文件播放)")
    else:
        print("当前没有正在播放的曲目")
else:
    print("授权失败,请检查用户名、权限及回调地址是否正确")

关键注意点

  • 必须添加playlist-read-private权限,否则无法读取私人播放列表详情。
  • 回调地址需与Spotify开发者后台配置完全一致,不能随意填写无效值。
  • 若当前播放单曲而非播放列表,context字段可能不存在或类型不符,需提前判断避免报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 23:30:28