Last active
October 12, 2024 14:02
-
-
Save rosmo/0c4d83fdd0e2625f6dbefcd880211e32 to your computer and use it in GitHub Desktop.
Control Spotify on Windows via API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Param | |
| ( | |
| [Parameter(Position=0)] | |
| [ValidateSet('play', 'stop')] | |
| [String] | |
| $Operation = $(throw "Operation is required (play or stop)."), | |
| [alias("Device")] | |
| [String] | |
| $DeviceName = $env:COMPUTERNAME, | |
| [String] | |
| $Track = "spotify:track:4BP3uh0hFLFRb5cjsgLqDh", | |
| [Parameter(Mandatory=$false)] | |
| [String] | |
| $ContextUri, # To play playlists or albums for example, eg. spotify:album:... or spotify:playlist:... (takes precedence) | |
| [Parameter(Mandatory=$false)] | |
| [nullable[bool]] | |
| $Shuffle, # To enable or disable shuffle when using ContextUri, if not specified, does not change state | |
| [String] | |
| $SpotifyExe = "spotify:" # UWP apps are launched through URL scheme | |
| ) | |
| Import-Module Spotify | |
| # Update the access token | |
| Update-SpotifyAccessToken | |
| # Check if Spotify is running, if not, start it | |
| if ((Get-Process "Spotify" -ErrorAction SilentlyContinue) -eq $Null) { | |
| Start-Process -FilePath $SpotifyExe | |
| } | |
| $DeviceId = $null | |
| $Attempt = 0 | |
| do { | |
| Get-SpotifyDevices | ForEach-Object { | |
| if ($_.name -eq $DeviceName) { | |
| $DeviceId = $_.id | |
| } | |
| } | |
| if ($DeviceId -eq $null) { | |
| # If the device isn't here yet, wait for 20 seconds until it appears | |
| Start-Sleep -Seconds 2 | |
| $Attempt++ | |
| } else { | |
| break | |
| } | |
| } while ($Attempt -lt 10) | |
| if ($DeviceId -eq $null) { | |
| throw "Unable to find Spotify device: $DeviceName" | |
| } | |
| switch ($Operation) { | |
| "play" { | |
| if (![string]::IsNullOrEmpty($ContextUri)) { | |
| if ($Shuffle -ne $null) { | |
| Set-SpotifyPlaybackShuffle -State $Shuffle -DeviceId $DeviceId | |
| } | |
| Start-SpotifyPlayback -ContextUri $ContextUri -DeviceId $DeviceId | |
| } else { | |
| Start-SpotifyPlayback -TrackUri $Track -DeviceId $DeviceId | |
| } | |
| } | |
| "stop" { | |
| Suspend-SpotifyPlayback -DeviceId $DeviceId | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment