Sign in as a Carbon or Silicon

Playback control

How play, pause, seek and the other controls reach Spotify.app, how every result is verified, and what happens when the first path fails.

The rule: the Web API first, verified, AppleScript fallback

spotify-cli drives Spotify through three paths:

So every start goes through the Spotify Web API first: songs, episodes, shows and Liked Songs directly, albums, playlists, artists and radios through spotify_player. Starts fall back to AppleScript, except a radio, which has no AppleScript way. Only exact seeks go to AppleScript first (AppleScript first).

For album, playlist, artist and radio starts and every other playback command but seek (strategy: auto, the default):

  1. Run the spotify_player command.
  2. Verify the effect in Spotify.app (AppleScript reads its state every 120 ms). spotify_player hands commands to its running instance asynchronously and exits 0 before anything happened, and some commands report success while doing nothing, so exit 0 is never trusted.
  3. If it errored, was refused, or did not take effect in time, run the AppleScript equivalent and verify again.
  4. Report which path worked:
JSONjson
{"action": "play", "via": "applescript",
 "fallback": {"from": "spotify_player", "reason": {"code": "no_effect", "message": "spotify_player accepted `play` but Spotify.app did not change within 1500 ms.", …}},
 "playback": {…}}

If both fail you get one path's error (usually AppleScript's verification_failed, retryable) with the other attempt in details (first_attempt, or second_attempt when spotify_player was tried second and could not run at all).

How long the first path gets before the fallback:

CommandsWait
play (resume), pause, toggle, volume, shuffleat most 1.5 s (less when verify_timeout_ms is smaller): they set a state, so a late effect only repeats the fallback's
next, previous, starts, seekverify_timeout_ms (default 2500 ms), then one more look 0.4 s later, so a late skip or seek is never applied twice
A Web API start (song, episode, show, Liked Songs)the same; a rate limit, missing Premium, a device that takes no Web API commands or no device to start on falls back at once, and a start whose answer was lost is first looked for in Spotify.app (Lost answers)
AppleScript itselfup to 2.5 s

Other strategies (spotify config set '{"strategy": "…"}'):

StrategyUse when
autodefault
applescriptno Premium, no spotify_player sign-in, or you want only local control. The Web API is never used: every start goes through AppleScript (Spotify.app comes forward and the focus goes back), and a radio cannot start
spotify_playeryou do not want AppleScript at all. Songs, episodes, shows and Liked Songs start through the Web API; when that fails only a song without --context and Liked Songs have a second way (spotify_player's own start, which loads a bare list of ids), else the error is unsupported with the Web API's attempt in details.first_attempt. Its seeks are approximate

Web API first: songs, episodes, shows and Liked Songs

spotify play <track> and spotify play <episode> (also play --search, podcast play and search --play when they pick a song or episode, and a song with --context), spotify play <show> and spotify play --liked start through the Spotify Web API directly. Not through spotify_player, which starts a song or Liked Songs as a bare list of ids that leaves Spotify.app stopped with nothing loaded, and cannot start a show; and not through AppleScript, whose play track brings Spotify.app to the front and takes the focus from the app you work in. The Web API tells Spotify.app, as a Spotify Connect device, what to play, and it plays where it is.

A song or an episode

  1. The item. GET /v1/tracks/{id} (or /v1/episodes/{id}) with market=from_token names the song's album or the episode's show, and, for a song that plays from another release in your market (relinked), that release. A song or episode Spotify lists as not playable in your market, with no release that plays there, fails at once (Not playable): nothing is sent and playback is not touched.
  2. The list. --context when you give one, else the song's album or the episode's show. So Spotify.app has a whole list loaded: after the song the album plays on (the show for an episode), and next and previous move through it.
  3. The device. Listed at every start (Where a start plays): the speaker or phone Spotify.app controls when one is active, else Spotify.app on this Mac.
  4. The start. PUT /v1/me/player/play?device_id=… with {"context_uri": <list>, "offset": {"uri": <item>}, "position_ms": 0}: the item, from its beginning, named as the list holds it. In its own album a relinked song is named by the id it links from (the album holds it under that id), so one request starts it (Relinked songs).
  5. The check. AppleScript reads Spotify.app every 120 ms (reads never bring it forward) until it plays the item: the id asked for, the release it plays from, or the same song relinked. Starting the song already loaded counts only once it went back to its start. It waits up to verify_timeout_ms (default 2500 ms), then looks once more 0.4 s later. When another track of the album starts instead, or Spotify refuses the item's uri in its album (400/404), the start is sent once more naming the track by its position in the album (counted across discs): the fallback when naming it by uri did not place it. A --context list is never retried by position.
JSONjson
{"action": "play", "via": "web_api", "playback": {…}}

Lookups are remembered for the life of the daemon (up to 500 items, not the ones that were not playable). The devices are not: they are listed at every start, because the active one changes whenever you pick a speaker in Spotify.app.

Not playable in your market

When the lookup says Spotify cannot play the song (or episode) in your country or market (is_playable: false) and names no other release that plays there, the start fails at once with not_playable (exit 1, not retryable):

JSONjson
{"code": "not_playable",
 "message": "'Fall (Acoustic Version)' by Ana Rey, The Tides (spotify:track:…) is not playable in your country/market: Spotify has no release of it that plays here, so nothing was started.",
 "hint": "Find another version with `spotify search 'Fall (Acoustic Version) Ana Rey' --type track`, then `spotify play <uri>`.",
 "details": {"uri": "spotify:track:…", "name": "Fall (Acoustic Version)", "market": "from_token", "reason": "market"}}

details.reason is the lookup's restrictions.reason when it gives one. market is the case above. Two reasons are about the account, not the country, and the message says so instead: explicit ("… is explicit, and this Spotify account is set not to play explicit content"; the hint also points to Spotify's explicit-content setting and searches for a clean version) and product ("… is not available on this account's Spotify plan").

No start is sent and nothing falls back: AppleScript's play track of such a song leaves Spotify.app with nothing loaded for a few seconds until what played before is put back. What played before keeps playing, untouched; the answer comes in about a second (one lookup of 0.3–0.6 s, and Spotify.app reads). A song that is relinked to a release that plays in your market is playable and starts as usual. Under strategy applescript there is no lookup, so AppleScript tries it.

A show

spotify play spotify:show:<id> sends {"context_uri": "spotify:show:<id>"} alone, so Spotify starts the show where it starts it, on the device chosen as for a song. It counts once Spotify.app plays something new (an episode, or an ad). spotify_player cannot start a show, so when this fails AppleScript plays it (play track <show uri>).

Liked Songs

spotify play --liked plays the Liked Songs list itself (spotify:user:<id>:collection, with the Spotify user id spotify_player is signed in as, read from its credentials.json), so next and previous stay in it. The result says via: web_api, action play_liked, and Spotify.app stays in the background.

  1. GET /v1/me/tracks?limit=1 gives how many songs Liked Songs holds and its first song (the one liked last). An empty Liked Songs is not_found at once and nothing starts. An answer that does not say how many is web_api_failed (retryable), and AppleScript starts the list.
  2. The start: at position 0, or, with --random (or --shuffle, which is the same with --liked), at a random position below that count. It counts once Spotify.app plays something new.
  3. Spotify keeps a shuffle setting per list and switches to Liked Songs' own when the list starts, so shuffle is set after the start, never before (that would only change the list playing before). That switch comes a moment after the first song shows: in one trace the first song showed with the shuffle of the list before (off), and Spotify.app turned shuffle on 75 ms later. So the controller first lets shuffle settle: it reads Spotify.app every 120 ms until neither shuffle nor the song changed for 0.45 s (at most 1.5 s), which adds about half a second to the start.
  4. When the settled shuffle differs from what was asked (off without --random, on with it), PUT /v1/me/player/shuffle sets it, and AppleScript's set shuffling does when that does not show in Spotify.app within 2.5 s.
  5. Without --random, when the list plays another song than its first (it started shuffled), it is started once more at position 0, so it plays in list order from the first song. When the first song already plays (shuffle came on only after it showed), turning shuffle off is enough.
  6. Whenever step 4 or 5 changed something, shuffle is let settle again and the result checked: shuffle as asked and, without --random, the first song. When Spotify switched it back, steps 4 and 5 run once more. The result is what Spotify.app keeps, e.g. shuffling: false on the first song for a plain play --liked.

Once Liked Songs plays, a step that does not show is verification_failed (retryable) saying which one, and so is a shuffle that Spotify switched back twice ("Spotify.app's shuffle did not stay off"); Liked Songs keeps playing and is not started a second time.

While Liked Songs plays, the Web API reports it as a playlist: GET /v1/me/player (and so spotify status --full's web) says "context_type": "playlist" and "context_uri": "spotify:playlist:37i9dQZF1F…", an id Spotify makes for your account (GET /v1/playlists/<id> names it "Liked Songs"), not spotify:user:<id>:collection, the uri that starts it. Both name the same list; to start Liked Songs use spotify play --liked.

When the Web API start fails, AppleScript plays the list, the focus goes back to your app, and the same result is reached its way once the start shows:

spotify_player's playback start liked (up to --limit tracks, default 200, as a list of ids that also empties the desktop app) runs only when the Spotify user id is unknown or under strategy spotify_player.

Where a start plays

Every Web API start lists GET /v1/me/player/devices first and picks:

When Spotify answers that the device is not found or that nothing is active (no_active_device: Spotify.app restarted, or the unlisted device went away), the devices are listed once more and the start goes to this Mac, unless another device is active by then.

When the answer is lost

A start answered with a server error (5xx), or not answered in time (a timeout or a broken connection; a connection that never opened sent nothing), may still have gone through. So the controller first looks for the item in Spotify.app, as for any start (the verify timeout, then one more look). When it plays, the start counts: via: web_api, with a note such as "The Spotify Web API gave HTTP 502 to the start, but Spotify.app plays it: the start went through, so it was not started again." Only when it does not play does the fallback start it, once. This covers songs, episodes, the retry by position, shows and Liked Songs (whose shuffle steps then follow as usual).

Fallback

When the start could not be sent or did not take effect, AppleScript plays it and verifies that. A song plays in the album the Web API's lookup named, named as that album holds it (play track <uri> in context <album>; a relinked song by the id it links from), so the album goes on after it, and Spotify.app showing either id counts. A song that is not playable never gets here. --context wins when given. The song plays alone when there was no lookup (the Web API unavailable) or when the album did not place it: Spotify refused it there by uri and by position, or another track of the album kept playing (no_effect with details.landed_elsewhere: true). An episode plays alone, a show and Liked Songs as themselves.

The outcome says fallback: {"from": "web_api", "reason": …}, and if AppleScript fails too, its error carries the Web API's attempt in details.first_attempt. fallback.reason.code:

CodeWhen
rate_limitedSpotify answered 429, or the pause after an earlier 429 still runs: nothing is sent until its Retry-After has passed (1 s to 10 minutes, 30 s when it gives none). The daemon's own Web API lookups and searches share that one pause. Falls back at once
premium_requiredthe account is not Premium: Spotify's Web API playback needs it. Falls back at once
device_restrictedthe active device takes no Web API commands (details.device: its name and type); AppleScript starts the item through Spotify.app, which controls that device
device_not_foundnothing else is active and no device in the list is clearly Spotify.app on this Mac (just launched, not yet registered, or offline); details.devices lists each device's name and type
no_active_deviceSpotify answered that the device is not found or nothing is active, also after the devices were listed again
spotify_auth_required, spotify_player_missingthe token is spotify_player's: it is not signed in, or not installed
web_api_failedany other HTTP status (details: request, status, message, reason, and unanswered: true for a 5xx that Spotify.app did not show), no album or show named for the item, a Liked Songs answer without its size, or spotify_player's cached token has expired (retryable)
not_found, transportSpotify does not know the item; the network (details: connect, timeout, and unanswered: true when the start may have left)
no_effectSpotify accepted the start but Spotify.app did not play the item in time (details: context, device, offset or position, observed, and for a song landed_elsewhere)

Under strategy applescript the Web API is never used; under strategy spotify_player there is no AppleScript fallback (see the strategies above).

Notes:

Keeping Spotify.app in the background

AppleScript's starts bring Spotify.app to the front, which steals the focus from the app you work in. So whenever AppleScript starts something (the fallback of a song, episode, show or Liked Songs start, an album or playlist that spotify_player could not start, the restore after a failed start, and managed-queue starts that use AppleScript), spotify-cli notes which app is in front, watches the front while the start runs and for 1 s after it, and as soon as Spotify.app takes it gives the focus back to that app (at most 3 times per start). If Spotify.app was hidden before, it is hidden again. In practice Spotify.app is in front for about half a second.

The outcome says what happened in refocused, e.g. {"app": "iTerm2", "via": "open"} (via is setfront or open), plus hid_spotify: true when Spotify.app was hidden again and error (code focus_not_returned) when macOS ignored both ways and Spotify.app stays in front. On a failed command it is details.refocused. It is never a command error. The daemon logs its queue's hand-backs.

Turn it off with spotify config set '{"keep_spotify_in_background": false}' (default true).

AppleScript first

Only exact seeks go to AppleScript first under auto, because spotify_player's way of doing them is worse on the desktop app. They report via: applescript with no fallback.

Every start goes to the Web API first: songs, episodes, shows and Liked Songs directly, albums, playlists, artists and radios through spotify_player (the rule). spotify_player starts a single song as a list of ids, which leaves Spotify.app stopped with nothing loaded, so it is never the fallback of a song start; it starts a song without --context only under strategy spotify_player, after the Web API. When any start falls back to AppleScript, the focus goes back to your app.

Checking spotify_player's view first

The running spotify_player instance decides what to send from its own memory of the player: whether it is playing, the repeat mode, shuffle, the current track. Its play does nothing while it believes playback runs, shuffle flips what it believes, like saves what it believes is playing. That memory can lag behind Spotify.app, so before such a command the controller reads it (get key playback, answered in milliseconds) and compares:

Commandspotify_player runs only when
play (resume)it believes playback is paused
pauseit believes playback runs
toggleas play or pause: toggle sends an explicit pause or play chosen from Spotify.app's state, never play-pause
shuffleits shuffle is Spotify.app's
next, previousit has playback loaded (next also: the Web API allows skipping from this item, else not_allowed_in_context and AppleScript skips)
seekit is on the item Spotify.app plays
repeatalways; it steps from the mode it believes and each step is confirmed (Repeat)
like, unlikeits track is the song Spotify.app plays, by id (Like and unlike)

A song Spotify plays under another id than Spotify.app shows counts as the same item, except for like and unlike (Relinked songs).

When they disagree under auto, AppleScript makes the change at once and fallback.reason.code is state_mismatch (details.spotify_player and details.spotify_app say what each believes). Under strategy spotify_player, state_mismatch is the error (retryable: retry after the next track change, or run spotify daemon restart). The daemon's spotify_player re-reads playback every 20 s (by default) and right after its own commands (spotify docs daemon), so after a change made in Spotify.app its view can be up to about 20 s behind; under auto that only means AppleScript makes the change.

Refusals are noticed at once

spotify_player exits 0 as soon as its running instance has the command; a Web API refusal (429, 403) then shows up only in that instance's log (spotify-player-<date>.log in its cache folder). The controller reads the lines logged after its own request, so a refusal ends the wait right away instead of after the verify timeout. The fallback reason is then:

CodeWhen
rate_limited429 Too Many Requests
no_active_devicespotify_player has no playback to send it to
no_effectany other refusal

with details.request (the request, e.g. Next) and details.spotify_player (the logged cause). Only a failure logged right after this command's own request counts, never another command's. A start whose second call (shuffle) was refused gets 1 s to show before anything else is tried. If spotify_player's log_folder is set outside its cache folder, refusals are not seen and commands wait for the timeout as before.

What each command does

CommandFirstThenVerified by
play (resume)playback playplaystate is playing
play <track>Web API PUT /me/player/play in its albumplay track <uri> in context <album>, named as the album holds it (the track alone when the album did not place it; none when it is not_playable)that track playing, relinked included (the track already loaded: restarted)
play <episode>Web API PUT /me/player/play in its showplay track <uri>that episode playing (already loaded: restarted)
play <track> --context <list>Web API PUT /me/player/play in <list>play track <uri> in context <list>that track playing, relinked included
play <album/playlist/artist>playback start context (--shuffle)play track <uri>a new item playing
play <show>Web API PUT /me/player/play with the show as the listplay track <uri>a new item playing
play --likedWeb API PUT /me/player/play in Liked Songs (its first song, or a random one), then its shuffleAppleScript: the Liked Songs list, then its shuffle stepsa new item playing, then each step
play --radioplayback start radionone (AppleScript has no radio)a new item playing
pauseplayback pausepausestate is not playing
toggleplayback pause or playback playpause or playstate flipped
nextplayback nextnext trackitem changed (or restarted by repeat-one)
previousplayback previous, or a restart (Previous)previous trackprevious item, or back at the start
seekAppleScript set player position (absolute)playback seek <offset> (relative)position within 1.5 s
volumeplayback volumeset sound volumethe exact level (Volume)
shuffleplayback shuffle (flips)set shufflingshuffling matches
repeat off/contextplayback repeat (steps)set repeatingSpotify.app's repeat flag
repeat trackplayback repeat (steps)none (AppleScript cannot)Spotify.app's repeat flag
like / unlikelike [--unlike]noneits track before and after

Notes:

Previous

From 3 s into the item, or when there is no item before it, previous restarts the current item (a seek to 0:00, the same way as seek) on every path, as Spotify.app's own button does; the Web API's previous would always go back an item. Otherwise it goes to the previous item. The outcome says which: result is restarted or previous_item, and the human output starts with "Back to the start of this item." or "Back to the previous item.".

Repeat

Spotify.app shows one repeat flag for both context and track, and AppleScript can only switch context repeat: set repeating false does not clear a repeat-one set through the Web API. So:

Volume

Spotify.app keeps the volume at 16-bit precision and reads most levels back one lower, so the AppleScript fallback sets one more when needed. It lands exactly on the requested level, except 19, 39, 59, 79 and 99, which land one above. Verification is exact (one above for those five).

Like and unlike

spotify_player's like has no id option: it saves or removes the track its instance believes is playing. So like and unlike:

When a start fails

When play <something> fails and leaves Spotify.app with nothing loaded although something was loaded before, the controller puts that back through AppleScript, under any strategy: the same track, in its playlist or album when spotify_player knew it, at the same position, paused if it was paused (and the focus goes back to your app). The error's details.restored holds the playback afterwards, or details.restore_failed says why it could not.

Status and the Web API

spotify status reads Spotify.app only (~50 ms). spotify status --full adds what only the Web API knows, under web: context_uri, context_type, device, repeat_state (tells repeat-one apart), shuffle_state, plus item_uri, is_playing, source, and stale and relinked (each present only when true).

Other warnings: no_active_device (the Web API sees no playback), timeout, rate_limited and spotify_player's own errors. Warnings never fail the command; the human output prints them as note: lines. When web.stale is true the human output takes repeat from Spotify.app's own flag (never "repeat one" from out-of-date data) and ends the flags line with "web data out of date". Time left, (-m:ss), is rounded to the nearest second (19.6 s left shows 0:20).

Relinked songs

When the release a song was saved or started from cannot play in your market, Spotify plays the same recording from another release (track relinking). Spotify.app then shows the id it was asked for, with the substitute's title, album and length, while the Web API, and so spotify_player, reports the substitute's id. spotify-cli counts the two as one song when the Web API item's linked_from names Spotify.app's id, or when the title (ignoring case and surrounding spaces), the length (within 1 s) and the album name agree. The same recording on a release with another album name (a single and its album, a deluxe edition) is another item.

Spotify.app not running

Reading state never launches Spotify. Control commands launch it hidden (open -g -j -a Spotify) when launch_spotify is true (default); set it false to get spotify_not_running instead. pause never launches it (spotify_not_running), and like/unlike need a song playing (nothing_playing). spotify launch starts it explicitly: "Started Spotify.app (hidden)." (launched: true), or "Spotify.app was already running." (launched: false, already_running: true, nothing opened).

Speed

The daemon keeps one headless spotify_player instance running on a pseudo-terminal it owns (streaming, media keys and notifications off, so it never becomes a playback device). With it, spotify_player commands take ~20 ms instead of ~1.5 s, and its view of playback is refreshed every 20 s (slow enough to leave Spotify's rate limit to commands). spotify daemon status shows it as warm spotify_player: running (…); details in spotify docs daemon.

A Web API start of a song or episode takes about 2–3 s end to end. In one traced start of 1.8 s, the item lookup took 0.35 s (with the TLS handshake), the device list 0.14 s and the play request 0.34 s, and Spotify.app showed the song about 0.3 s later. The daemon keeps one HTTPS connection for these requests, and a later start of the same item skips the lookup; the device list is read at every start, so a start follows the speaker you just picked.

Known limits

Offline: spotify docs playback · Source: docs/playback.md