如何使用Spotipy获取当前播放歌曲的封面图片?
使用Spotipy获取当前播放曲目封面并显示的方法
完全可以通过Spotipy实现这个需求,具体步骤如下:
1. 确保授权包含必要权限
要获取用户当前播放状态,你的Spotify开发者应用必须申请user-read-currently-playing权限。初始化Spotipy客户端时需指定该权限:
import spotipy from spotipy.oauth2 import SpotifyOAuth sp = spotipy.Spotify(auth_manager=SpotifyOAuth( client_id="你的客户端ID", client_secret="你的客户端密钥", redirect_uri="http://localhost:8080", scope="user-read-currently-playing" ))
2. 获取当前播放曲目及封面URL
调用current_user_playing_track()方法获取播放信息,返回的字典中,item['album']['images']包含不同分辨率的封面链接,默认按清晰度从高到低排序:
current_track = sp.current_user_playing_track() if current_track and current_track['item']: # 取最高清的封面链接 cover_url = current_track['item']['album']['images'][0]['url'] else: print("当前没有正在播放的曲目")
3. 显示封面到独立窗口
用PIL配合tkinter就能快速实现窗口显示,先安装依赖:
pip install pillow tk
然后编写显示逻辑:
import tkinter as tk from PIL import Image, ImageTk import requests from io import BytesIO def show_cover(cover_url): # 从URL拉取图片数据 response = requests.get(cover_url) img = Image.open(BytesIO(response.content)) # 创建显示窗口 window = tk.Tk() window.title("当前曲目封面") # 转换图片格式适配tkinter tk_img = ImageTk.PhotoImage(img) label = tk.Label(window, image=tk_img) label.pack() # 保留图片引用避免被垃圾回收 label.image = tk_img window.mainloop() # 调用显示函数 if 'cover_url' in locals(): show_cover(cover_url)
注意事项
- 若当前无播放曲目,
current_user_playing_track()会返回None,需做好空值判断 images数组可按需选择尺寸,比如用[-1]取最低清版本,适合小窗口显示- 确保网络能访问Spotify的图片CDN,否则无法加载封面
内容的提问来源于stack exchange,提问作者frzzled
相关产品推荐
相关产品推荐

