import spotipy from spotipy.oauth2 import SpotifyOAuth import os client_id = "884910ea1cf64450ad87385ac08787b2" client_secret = "32778c81ccec4d42a159e0ef890a1900" redirect_uri = "http://127.0.0.1:8888/callback" target_device_name = 'raspotify (murphy)' # Set your environment variables first, or replace the `os.environ` calls # with your actual Client ID, Client Secret, and Redirect URI. scope = "user-read-playback-state,user-modify-playback-state" sp = spotipy.Spotify(auth_manager=SpotifyOAuth( client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri, scope=scope )) def get_device_id_by_name(sp_obj, device_name): """ Finds a device ID by its name from the list of available devices. Args: sp_obj: The Spotipy authenticated object. device_name (str): The human-readable name of the device. Returns: str: The device ID if found, otherwise None. """ try: devices = sp_obj.devices() for device in devices['devices']: if device['name'] == device_name: return device['id'] return None except spotipy.SpotifyException as e: print(f"Error fetching devices: {e}") return None # Find an active Spotify Connect device. The Spotify app must be open and playing music on the device. devices = sp.devices() if not devices['devices']: print("No active Spotify devices found. Please start playback on a device.") else: # Loop through the devices and print their names and IDs for d in devices['devices']: print(f"Device Name: {d['name']}, ID: {d['id']}, Type: {d['type']}") #device_id = devices['devices'][0]['id'] #print(f"Controlling device: {devices['devices'][0]['name']}") # Define your search query with specific field filters artist_name = "[spunge]" track_name = "Jump On Demand" query = f'artist:"{artist_name}" track:"{track_name}"' # Perform the search results = sp.search(q=query, type='track', limit=1) if not results['tracks']['items']: print("Track not found.") else: track_uri = results['tracks']['items'][0]['uri'] print(f"Found track: {results['tracks']['items'][0]['name']}") print(f"Track URI: {track_uri}") # Get the device ID using the function chosen_device_id = get_device_id_by_name(sp, target_device_name) if chosen_device_id: print(f"Playing on device '{target_device_name}' with ID: {chosen_device_id}") try: sp.start_playback(device_id=chosen_device_id, uris=[track_uri]) print("Playback started successfully.") except spotipy.SpotifyException as e: print(f"Error starting playback: {e}") else: print(f"Device '{target_device_name}' not found. Please check device name and ensure it's active.") # Start playback of the track on the active device #sp.start_playback(device_id=device_id, uris=[track_uri]) #print(f"Now playing: {results['tracks']['items'][0]['name']}") # Example of other playback controls #print("\nPausing playback...") #sp.pause_playback(device_id=device_id) #print("Resuming playback...") #sp.start_playback(device_id=device_id)