Jump to content

Start Spotify and play a playlist


boomingranny
 Share

Recommended Posts

;******************************************************************
;Spotify Automation: Start spotify and play a playlist
;v1.01  27/04/2018
;------------------------------------------------------------------
;by Daniel Barnes
;------------------------------------------------------------------
;v1.01  27/04/2018
;restarts spotify if it fails the first time
;works on computers that minimize Spotify to tray
;instead of closing it, and have a different ui element selected
;such as the Devices available option when spotify is started
;------------------------------------------------------------------
;v1.00 25/04/2018
;initial version
;------------------------------------------------------------------

;Replace the below with the Spotify URI
;If you right click the playlist> share> copy spotify uri
;you can find the uri
$spotifyURI = "spotify:user:12177300374:playlist:0iaTAvHRSaIkD23ofl2tck"
;******************************************************************

;if this script breaks in the future, figure this out using the AutoIt Window Info Tool
Const $SpotifyWindowIdentifier = "[Title:Spotify;Class:Chrome_WidgetWin_0]"

;NOTE ABOUT SHUFFLE:
;I couldn't automate turning shuffling on or off
;I can toggle it, but I cannot figure out the current state
;If you want to shuffle, turn on shuffle in Spotify prior
;to running this script

PlaySpotifyPlaylist($spotifyURI)

Func PlaySpotifyPlaylist($spotifyURI,$retry = 0)
    ;terminate spotify process on subsequent attempts
    If $retry Then
        echo ("Closing existing Spotify process")
        ProcessClose("Spotify.exe")
    endif

    echo ("Launching Spotify URI")
    ShellExecute($spotifyURI)

    ;Pause any existing song playing (if there is any)
    ;this is because Spotify's window title is only 'Spotify' when it is not playing any songs
    If Not WinExists($SpotifyWindowIdentifier) Then
        echo ("Pausing existing song (To find spotify window)")
        $timer = TimerInit()
        While Not WinExists($SpotifyWindowIdentifier)
            Send("{MEDIA_PLAY_PAUSE}")
            Sleep(500)
            If TimerDiff($timer) > 5 * 1000 Then ErrorMsg ("Timed out trying pause existing song")
        WEnd
    endif

    ;Get Spotify Window Handle
    $hwndSpotify = WinGetHandle($SpotifyWindowIdentifier)

    echo ("Attempting to play playlist")
    $timer = TimerInit()
    While WinGetTitle($hwndSpotify) = "Spotify" ;once it is playing the song, the title changes to the name of the song
        WinActivate($hwndSpotify)
        ControlSend($hwndSpotify,"","","{ENTER}") ;space will play what was previously playing (even another playlist or song), enter will play the playlist ;)
        Sleep(1000)
        If TimerDiff($timer) > 5 * 1000 Then
            If $retry Then
                ErrorMsg ("Timed out trying to play playlist")
            else
                Return PlaySpotifyPlaylist($spotifyURI,$retry+1)
            endif
        endif
    WEnd
EndFunc

Func echo($text)
    ConsoleWrite ($text&@CRLF)
EndFunc

Func ErrorMsg($text)
    MsgBox(16,StringTrimRight(@ScriptName,4),$text)
    Exit
EndFunc

 

Edited by boomingranny
v1.01
Link to comment
Share on other sites

  • 3 months later...

Wow thanks for this script!  For different versions of spotify this will have problems for sure.. only because spotify sux.

The version I am running 1.0.86.337.ga8d5cef9 does not work with just your script.  I had to make the following adjustments:

1) Always close spotify at the beginning (to ensure tab selection is reset)

2) Just pressing enter does not play the playlist.  Need to shift tab 3x times, press enter, then press tab 2x times, then press enter.

Also the retry was triggering even though the song was playing, so I got rid of that.

I also added the ability to pass in a parameter to play a playlist

;******************************************************************
;Spotify Automation: Start spotify and play a playlist
;v1.01  27/04/2018
;------------------------------------------------------------------
;by Daniel Barnes
;------------------------------------------------------------------
;v1.01  27/04/2018
;restarts spotify if it fails the first time
;works on computers that minimize Spotify to tray
;instead of closing it, and have a different ui element selected
;such as the Devices available option when spotify is started
;------------------------------------------------------------------
;v1.00 25/04/2018
;initial version
;------------------------------------------------------------------

Local $uriIndex[][2] = [ _
   ["OFF",                      "OFF"], _
   ["playlistname1",            "spotify:user:user:playlist:UIRCODE"], _
   ["playlistname2",            "spotify:user:user:playlist:UIRCODE"], _
   ["playlistname3",            "spotify:user:user:playlist:UIRCODE"] _
]

;Replace the below with the Spotify URI
;If you right click the playlist> share> copy spotify uri
;you can find the uri
$spotifyURI = ""
;******************************************************************

;if this script breaks in the future, figure this out using the AutoIt Window Info Tool
Const $SpotifyWindowIdentifier = "[Title:Spotify;Class:Chrome_WidgetWin_0]"

;NOTE ABOUT SHUFFLE:
;I couldn't automate turning shuffling on or off
;I can toggle it, but I cannot figure out the current state
;If you want to shuffle, turn on shuffle in Spotify prior
;to running this script

if($CmdLine[0] == 0) Then
   MsgBox(0, "Spotify Au3 Script Error", "No Parameters")
ElseIf($CmdLine[0] >= 1) Then
   Local $spotifyURI = ""
   for $i = 0 To UBound($uriIndex)-1 Step 1
      if($CmdLine[1] = $uriIndex[$i][0]) Then
         $spotifyURI = $uriIndex[$i][1]
         ExitLoop
      EndIf
   Next
   if($spotifyURI = "") Then
      MsgBox(0, "Spotify Au3 Error", "Unable to find spotify uri with key: " & $CmdLine[1])
   Else
      if($spotifyURI = "OFF") Then
         ProcessClose("Spotify.exe")
      Else
         PlaySpotifyPlaylist($spotifyURI)
      Endif
   EndIf
EndIf

Func PlaySpotifyPlaylist($spotifyURI,$retry = 0)
    ;terminate spotify process on subsequent attempts
    ;If $retry Then
        echo ("Closing existing Spotify process")
        ProcessClose("Spotify.exe")
    ;endif

    echo ("Launching Spotify URI")
    ShellExecute($spotifyURI)

    ;Pause any existing song playing (if there is any)
    ;this is because Spotify's window title is only 'Spotify' when it is not playing any songs
    If Not WinExists($SpotifyWindowIdentifier) Then
        echo ("Pausing existing song (To find spotify window)")
        $timer = TimerInit()
        While Not WinExists($SpotifyWindowIdentifier)
            Send("{MEDIA_PLAY_PAUSE}")
            Sleep(500)
            If TimerDiff($timer) > 5 * 1000 Then ErrorMsg ("Timed out trying pause existing song")
        WEnd
    endif

    ;Get Spotify Window Handle
    $hwndSpotify = WinGetHandle($SpotifyWindowIdentifier)

    echo ("Attempting to play playlist")
    $timer = TimerInit()
    ;While WinGetTitle($hwndSpotify) = "Spotify" ;once it is playing the song, the title changes to the name of the song
        Sleep(5000)
        WinActivate($hwndSpotify)
        ;ControlSend($hwndSpotify,"","","{ENTER}") ;space will play what was previously playing (even another playlist or song), enter will play the playlist ;)
        ControlSend($hwndSpotify,"","","+{TAB}")
        ControlSend($hwndSpotify,"","","+{TAB}")
        ControlSend($hwndSpotify,"","","+{TAB}")
        ControlSend($hwndSpotify,"","","{ENTER}")
        ControlSend($hwndSpotify,"","","{TAB}")
        ControlSend($hwndSpotify,"","","{TAB}")
        ControlSend($hwndSpotify,"","","{ENTER}")

        ;Sleep(1000)
        ;If TimerDiff($timer) > 5 * 1000 Then
        ;    If $retry Then
        ;        ErrorMsg ("Timed out trying to play playlist")
        ;    else
        ;        Return PlaySpotifyPlaylist($spotifyURI,$retry+1)
        ;    endif
        ;endif
    ;WEnd
EndFunc

Func echo($text)
    ConsoleWrite ($text&@CRLF)
EndFunc

Func ErrorMsg($text)
    MsgBox(16,StringTrimRight(@ScriptName,4),$text)
    Exit
EndFunc

 

Link to comment
Share on other sites

  • 4 months later...

Thanks for the scripts above - I have been using them extensively from my home automation system.

I just noticed that it wasn't working again.  I played around and came up with the following combination when loading a URI to get it to play:

   ControlSend($hwndSpotify,"","","{ENTER}")
   ControlSend($hwndSpotify,"","","+{TAB}")
   ControlSend($hwndSpotify,"","","+{TAB}")
   ControlSend($hwndSpotify,"","","+{TAB}")
   ControlSend($hwndSpotify,"","","+{TAB}")
   ControlSend($hwndSpotify,"","","{TAB}")
   ControlSend($hwndSpotify,"","","{TAB}")
   ControlSend($hwndSpotify,"","","{TAB}")
   ControlSend($hwndSpotify,"","","{TAB}")
   ControlSend($hwndSpotify,"","","{TAB}")
   ControlSend($hwndSpotify,"","","{ENTER}")
 

Not sure if this is the most elegant way to do this but it works.

Link to comment
Share on other sites

  • 2 weeks later...

Thanks Simon!  Noticed mine was not working and made your changes.  I had to add some sleeps between the commands... maybe because the computer is a bit slow.... but it works!

Yeah, the Ctrl Right arrow never worked for me either.  Honestly I am kinda fed up with Spotify's crappy client.  You can find and download older versions of the client that have better automation capability ( and disable upgrading ).  I might do that again to avoid having to update scripts.  I used to run a script on an older spotify client (pre- 1.0) that would select the current song, grab its name (for writing to a file) and delete it.  Was cool for "blowing up" songs.

Link to comment
Share on other sites

  • 3 weeks later...

ok, it stopped working again so I started playing with it.  I decided to go in another direction.  I am now doing the following:

   ControlSend($hwndSpotify,"","","^s")
   ControlSend($hwndSpotify,"","","^r")
   MouseClick($MOUSE_CLICK_LEFT, 400, 250, 2)

This is clicking the PLAY button after turning on shuffle and repeat.  The playlist is loaded in the command line.

This works most of the time.  Weirdly it seems to fail when I haven't played Spotify in a while.  But if I repeat the process all over again (loading spotify and issuing these commands) then it works.  I am trying to figure out what happens when Spotify is not loaded for a while.

Also, the X,Y is set for resolution my server runs at 1024x768.  It needs to be adjusted according to resolution.

One thing that I would like to do is test the PLAY/PAUSE button for state.  That would allow me to see if the click has worked.  I am not that familiar with autoit so if someone wants to jump in and help in identifying the button and how to test for the state - PLAY or PAUSE - I could always use the help.  I have attached the script, not the prettiest thing but I usually leave all of the commands in it that have failed so I don't go over old ground again.

 

As an aside they have improved their API - https://developer.spotify.com/documentation/web-api/reference-beta/ - I am not that familiar with this approach but I guess I will need to start learning how to do it.

SpotifyLauncher.au3

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...