[GH-ISSUE #685] Playing a song on Spotify when not previously playing #404

Closed
opened 2026-02-27 23:22:26 +03:00 by kerem · 5 comments
Owner

Originally created by @evanlaf on GitHub (May 29, 2021).
Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/685

Hi, I am using Windows 10 and Python 3.8 for Spotipy. I already validated the user connection, and found that I could play a song only if spotify is already running. For example, I can change the song that currently plays on my phone with the code below. However, my goal is to play a song when Spotify is not already playing, e.g., start Spotify and play a song. If Spotify is not already running, I receive an error message (also shown below). This can be solved by directly connecting with the Spotify web api like this, and I cannot find whether this is possible through spotipy; has anyone run into this issue and was able to solve it without directly talking to the web api?

Code:

import spotipy
from spotipy.oauth2 import SpotifyOAuth

scope = "user-library-read,playlist-read-private,user-read-playback-state,user-modify-playback-state"

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope, client_id='client-id', client_secret='client-secret', redirect_uri='http://localhost:58000'))

sp.start_playback(uris=['spotify:track:7dt6x5M1jzdTEt8oCbisTK'])

Error when spotify is not already playing:

HTTP Error for PUT to https://api.spotify.com/v1/me/player/play returned 404 due to Player command failed: No active device found
Traceback (most recent call last):
  File "C:\Users\el\AppData\Local\Programs\Python\Python38-32\lib\site-packages\spotipy\client.py", line 245, in _internal_call
    response.raise_for_status()
  File "C:\Users\el\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 943, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://api.spotify.com/v1/me/player/play

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "spotify.py", line 9, in <module>
    sp.start_playback(uris=['spotify:track:7dt6x5M1jzdTEt8oCbisTK'])
  File "C:\Users\el\AppData\Local\Programs\Python\Python38-32\lib\site-packages\spotipy\client.py", line 1761, in start_playback
    return self._put(
  File "C:\Users\el\AppData\Local\Programs\Python\Python38-32\lib\site-packages\spotipy\client.py", line 306, in _put
    return self._internal_call("PUT", url, payload, kwargs)
  File "C:\Users\el\AppData\Local\Programs\Python\Python38-32\lib\site-packages\spotipy\client.py", line 261, in _internal_call
    raise SpotifyException(
spotipy.exceptions.SpotifyException: http status: 404, code:-1 - https://api.spotify.com/v1/me/player/play:
 Player command failed: No active device found, reason: NO_ACTIVE_DEVICE
Originally created by @evanlaf on GitHub (May 29, 2021). Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/685 <!--- Please make sure you've: - read the FAQ https://github.com/plamere/spotipy/blob/master/FAQ.md - read the documentation https://spotipy.readthedocs.io/en/latest/ - searched older issues If your question is about code, please share the code you are using ---> Hi, I am using Windows 10 and Python 3.8 for Spotipy. I already validated the user connection, and found that I could play a song _only if_ spotify is already running. For example, I can change the song that currently plays on my phone with the code below. However, my goal is to play a song when Spotify is not already playing, e.g., start Spotify and play a song. If Spotify is not already running, I receive an error message (also shown below). This can be solved by directly connecting with the Spotify web api like [this](https://community.spotify.com/t5/Spotify-for-Developers/active-a-playback-device-with-API/td-p/4963267), and I cannot find whether this is possible through spotipy; has anyone run into this issue and was able to solve it without directly talking to the web api? Code: ``` import spotipy from spotipy.oauth2 import SpotifyOAuth scope = "user-library-read,playlist-read-private,user-read-playback-state,user-modify-playback-state" sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope, client_id='client-id', client_secret='client-secret', redirect_uri='http://localhost:58000')) sp.start_playback(uris=['spotify:track:7dt6x5M1jzdTEt8oCbisTK']) ``` Error when spotify is not already playing: ``` HTTP Error for PUT to https://api.spotify.com/v1/me/player/play returned 404 due to Player command failed: No active device found Traceback (most recent call last): File "C:\Users\el\AppData\Local\Programs\Python\Python38-32\lib\site-packages\spotipy\client.py", line 245, in _internal_call response.raise_for_status() File "C:\Users\el\AppData\Local\Programs\Python\Python38-32\lib\site-packages\requests\models.py", line 943, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://api.spotify.com/v1/me/player/play During handling of the above exception, another exception occurred: Traceback (most recent call last): File "spotify.py", line 9, in <module> sp.start_playback(uris=['spotify:track:7dt6x5M1jzdTEt8oCbisTK']) File "C:\Users\el\AppData\Local\Programs\Python\Python38-32\lib\site-packages\spotipy\client.py", line 1761, in start_playback return self._put( File "C:\Users\el\AppData\Local\Programs\Python\Python38-32\lib\site-packages\spotipy\client.py", line 306, in _put return self._internal_call("PUT", url, payload, kwargs) File "C:\Users\el\AppData\Local\Programs\Python\Python38-32\lib\site-packages\spotipy\client.py", line 261, in _internal_call raise SpotifyException( spotipy.exceptions.SpotifyException: http status: 404, code:-1 - https://api.spotify.com/v1/me/player/play: Player command failed: No active device found, reason: NO_ACTIVE_DEVICE ```
kerem 2026-02-27 23:22:26 +03:00
  • closed this issue
  • added the
    question
    label
Author
Owner

@Peter-Schorn commented on GitHub (May 29, 2021):

If you want to play content when no device is active, you must provide a device id to the Spotify.start_playback method. You can find the ids of the available devices using the Spotify.devices endpoint.

This can be solved by directly connecting with the Spotify web api like this, and I cannot find whether this is possible through spotipy

All of the Spotify web API endpoints, including the ones mentioned in the article you linked, are supported by spotipy:

https://developer.spotify.com/documentation/web-api/reference/player/transfer-a-users-playback/ -> Spotify.transfer_playback.

https://developer.spotify.com/documentation/web-api/reference/player/get-a-users-available-devices/ -> Spotify.devices.

<!-- gh-comment-id:850907306 --> @Peter-Schorn commented on GitHub (May 29, 2021): If you want to play content when no device is *active*, you must provide a device id to the `Spotify.start_playback` method. You can find the ids of the available devices using the `Spotify.devices` endpoint. > This can be solved by directly connecting with the Spotify web api like this, and I cannot find whether this is possible through spotipy All of the Spotify web API endpoints, including the ones mentioned in the article you linked, are supported by spotipy: https://developer.spotify.com/documentation/web-api/reference/player/transfer-a-users-playback/ -> `Spotify.transfer_playback`. https://developer.spotify.com/documentation/web-api/reference/player/get-a-users-available-devices/ -> `Spotify.devices`.
Author
Owner

@evanlaf commented on GitHub (May 30, 2021):

@Peter-Schorn Thanks for the comment. I looked into using those, and am still running into a similar issue. Either through their web console or in spotipy (e.g., sp.devices()), I can see the list of active devices and get the running device's id. Then, passing in the device id (e.g., sp.start_playback(uris=['track'], device_id='device_id')) works if the device is active, but not if the device is inactive.

So, passing in an inactive device's id does not allow Spotify to play on the local device. A workaround would be to always have a Spotify instance running on the local device, but as I want to use spotipy on a Raspberry Pi, I don't think that is a valid solution. What are your thoughts?

<!-- gh-comment-id:851007039 --> @evanlaf commented on GitHub (May 30, 2021): @Peter-Schorn Thanks for the comment. I looked into using those, and am still running into a similar issue. Either through their web console or in `spotipy` (e.g., `sp.devices()`), I can see the list of active devices and get the running device's id. Then, passing in the device id (e.g., `sp.start_playback(uris=['track'], device_id='device_id')`) works if the device is active, but not if the device is inactive. So, passing in an inactive device's id does not allow Spotify to play on the local device. A workaround would be to always have a Spotify instance running on the local device, but as I want to use `spotipy` on a Raspberry Pi, I don't think that is a valid solution. What are your thoughts?
Author
Owner

@Peter-Schorn commented on GitHub (May 30, 2021):

I can see the list of active devices and get the running device's id.

No, you can see the list of available devices and see which one (singular) is active by checking theis_active property of each device object in the list of devices.

Do not confuse an available device with an active device. A device is available if it shows up in the list of devices returned by the devices method. In order for a device to be available, it must be open (e.g., the Spotify desktop application must be open for it to be considered available).

A device becomes active when you pay content on it. When playback ceases, it typically becomes inactive only a few minutes later. A device immediately becomes inactive if you close the device or start playback on another device.

You can play content on any available device, whether it's active or not. If a device does not show up in the list of devices returned by the devices method, then it's considered unavailable and you cannot play content on it.

A workaround would be to always have a Spotify instance running on the local device

You must have a spotify client (e.g, the desktop application) open in order to play content. The web API will not open a client for you. That's not how it works.

but as I want to use spotipy on a Raspberry Pi,

I'm not sure I understand the relevance of this part. Are you running the Spotify desktop application/ web player on the raspberry pi? If you're merely communicating with the web API programmatically using spotipy, then the hardware you're using is irrelevant.

<!-- gh-comment-id:851022827 --> @Peter-Schorn commented on GitHub (May 30, 2021): > I can see the list of active devices and get the running device's id. No, you can see the list of _available_ devices and see which one (singular) is _active_ by checking the`is_active` property of each device object in the list of devices. Do not confuse an _available_ device with an _active_ device. A device is _available_ if it shows up in the list of devices returned by the `devices` method. In order for a device to be available, it must be open (e.g., the Spotify desktop application must be open for it to be considered available). A device becomes _active_ when you pay content on it. When playback ceases, it typically becomes inactive only a few minutes later. A device immediately becomes inactive if you close the device or start playback on another device. You can play content on any available device, whether it's active or not. If a device does not show up in the list of devices returned by the `devices` method, then it's considered unavailable and you cannot play content on it. > A workaround would be to always have a Spotify instance running on the local device You _must_ have a spotify client (e.g, the desktop application) open in order to play content. The web API will not open a client for you. That's not how it works. > but as I want to use spotipy on a Raspberry Pi, I'm not sure I understand the relevance of this part. Are you running the Spotify desktop application/ web player on the raspberry pi? If you're merely communicating with the web API programmatically using `spotipy`, then the hardware you're using is irrelevant.
Author
Owner

@evanlaf commented on GitHub (May 30, 2021):

Ah yes I was confusing that terminology, thanks for the clarification. I did additional research and found that you can make a device a Spotify connect device, then play music off of that. This is especially useful in terms on running a device like the rpi. The reason I mentioned this is because of limited memory capabilities on the rpi and I don't see the need to have an application running 24/7 if it's only being time to time.

You must have a spotify client (e.g, the desktop application) open in order to play content. The web API will not open a client for you. That's not how it works.

This was my original question, which makes sense, but was not clarified anywhere. I will most likely write a script that opens the Spotify application prior to playing music through spotipy (and closes Spotify afterwards) due to the API's limited capabilities. Thanks for the clarifications.

<!-- gh-comment-id:851044555 --> @evanlaf commented on GitHub (May 30, 2021): Ah yes I was confusing that terminology, thanks for the clarification. I did additional research and found that you can make a device a Spotify connect device, then play music off of that. This is especially useful in terms on running a device like the rpi. The reason I mentioned this is because of limited memory capabilities on the rpi and I don't see the need to have an application running 24/7 if it's only being time to time. > You must have a spotify client (e.g, the desktop application) open in order to play content. The web API will not open a client for you. That's not how it works. This was my original question, which makes sense, but was not clarified anywhere. I will most likely write a script that opens the Spotify application prior to playing music through `spotipy` (and closes Spotify afterwards) due to the API's limited capabilities. Thanks for the clarifications.
Author
Owner

@olsonap commented on GitHub (Oct 28, 2021):

The way I handled this was

try:
        track = spotifyObject.current_playback()
except:
       update_device()


def update_device()
      devices = spotifyObject.devices()
      for device in devices:
            if device["is_active"] == True:
                deviceID = device["id"]
                deviceType = device["name"]
                break
            else:
                deviceID = ""
        if deviceID == "":
            deviceID = "[insert default speaker id here]"
            deviceType = "Default Speaker"

Then, you'd have to initiate playback somewhere using

spotifyObject.start_playback(self.deviceID)
<!-- gh-comment-id:954109914 --> @olsonap commented on GitHub (Oct 28, 2021): The way I handled this was ``` try: track = spotifyObject.current_playback() except: update_device() def update_device() devices = spotifyObject.devices() for device in devices: if device["is_active"] == True: deviceID = device["id"] deviceType = device["name"] break else: deviceID = "" if deviceID == "": deviceID = "[insert default speaker id here]" deviceType = "Default Speaker" ``` Then, you'd have to initiate playback somewhere using ``` spotifyObject.start_playback(self.deviceID) ```
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/spotipy#404
No description provided.