-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathspotify_play_song.py
38 lines (37 loc) · 1.29 KB
/
spotify_play_song.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import os
import pickle
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from spotipy.oauth2 import SpotifyClientCredentials
def spotify_play_song(song_name):
# Load spotify credentials
credentials_path = './credentials/spotify/token.pickle'
if os.path.exists(credentials_path):
with open(credentials_path, 'rb') as token_file:
spotify_token = pickle.load(token_file)
else:
raise FileNotFoundError("Spotify token file not found.")
token_info = SpotifyOAuth(token=spotify_token)
# Initialization
if not token_info:
print("No account found")
return None
else:
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
if sp is None:
return None
# Get track uri from the song name
# '''searches song name and finds the most popular match and then provides the URI from that'''
results = sp.search(q=song_name, type='track', limit=1)
tracks = results['tracks']['items']
if tracks:
song = tracks[0]['uri']
else:
print("No tracks found for:", song_name)
return None
# Uses the URI to play the song on Spotify
try:
sp.start_playback(uris=[song])
print("Playing")
except spotipy.SpotifyException as e:
print("Error", e)