Jump to content
Sign in to follow this  
boomingranny

Start Spotify and play a playlist

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

Share this post


Link to post
Share on other sites

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

 

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Also, I tried to add a CTRL RIGHT ARROW to the end to advance to the next track (otherwise it always starts on the same track when loading the playlist.  I couldn't get the syntax for this to work.  {^RIGHT} didn't work.

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
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
Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By WilliamasKumeliukas
      Hi,
      I started this project alone in May 2020 as project in my spare time at work, I'm working for a IT compagny that's started opening their services to residential customers few months ago and now my position in the company kinda drifted in the doom and gloom world of repetitive tasks like: Reinstallation of Windows 10.
      The procedure is very repetitive and I started feeling like being a robot which is the main reason I started this project.
       
      ==============================FAQ==================================
      1. Q: Do you want this project to be accomplished with the usage of AutoIT ONLY or 3rd party tools / Scripts (BAT / CMD / VBS) ? A: No, if I cannot find a way using AutoIT to accomplish a task I will move to my Plan B which consist of automating an 3rd party tool to accomplish the affected task until a solution is found. 2. Q: What do I get from helping/collaborating in this project? A: I will personally take the responsability to mention you in the credits of this project. 3. Q: If I have more questions, can I ask? A: Certainly! feel free to ask any questions related to this project! 4. Q: What is the main goal of this project? A: Automating Windows 10 configuration without user interaction needed (as much as possible) ______________________________________________________________________________________________________________________________
      Current progression of the project (more might be added in future)
      « Blue = Info || Yellow = Unfinished/Untested || Purple = Could be better || Green = Done ||Red = Not Yet Started »
      *** Very early Stage ***
      Connect Network Attached Storage(NAS) (Tested & Working - AutoIT only)
      Install Adobe Reader DC, 7zip, Google Chrome (Tested & Working - using 3rd party tool)
      Change OEM Information (Tested & Working - contains both AutoIT version and CMD script)
      Disable ScreenSaver (Require testing AutoIT only)
      Change Computer Name (Require testing AutoIT only) 
      Change Default Browser (Work - using 3rd party tool)
      Change .pdf / .pdfxml from Edge to Adobe Reader DC (AutoIT only)
      Change Edge to Google Chrome as Default Browser (Tested & Working - using 3rd party tool)
      Windows Updates (Currently working on it - AutoIT only)
      Install Office 
      Activate Office (Tested on 2010 & Working - CMD Script)
      Pin to taskbar Excel, Outlook, Word, Chrome (Tested & Working - using 3rd party tool)
      GUI currently featuring the following options 
      - TreeView to check case of desired tasks
      -  Redirect ConsoleWrite with timestamp messages in richedit (errors shown in red text)
                 *** To Do ***
       - Read informations needed for tasks like: OEM, ComputerName, NAS user/password etc... from a file
       - ListView for Windows Updates
       - Probably more
       
      ***  If this project interest you, Reply here This will greatly help me to see if you'd like this project to become real  ***
      ______________________________________________________________________________________________________________________________
      2020.09.21 Update: Since this topic reached over 200+ views without a single interest shown by community, pm me and i'll share with you W10 Configurator script  
       
      Best Regards,
      ~WilliamasKumeliukas
    • By WindIt
      Hi, 
      I have a set of excel docs 1& 2
      1) In Excel 1 i have a fixed column called dimensionId that contains list of dimensionid's with in between empty cells.
      Here, For each dimesionId, i need to check corresponding columns of L,M,N ,O(senior, mid, junior, student) & check If they contain letter Y (Open excel 2) and if empty ignore,check next.
      I need to loop through the entire column of dimensionId one by one, please help me proceed with the logic.
      2) If letter Y exists, open excel 2 and check if same dimesionId exists in column A.
      New to autoit excel automation, Help me with logic to execute this.
      #include <Excel.au3>
      Global $oExcel = _Excel_Open()
      Global $oWorkbook = _Excel_BookOpen($oExcel, "D:\yta\Trial concept dimensions list.xlsx")
      Local $read1 = _Excel_RangeRead ($oWorkbook,Default,"C3")
      MsgBox(0,"",$read1)
      Attached exce 1 doc.
       
       
      exl1.xlsx exl2.xlsx
    • By Earthshine
      This is pretty useful to me at least, I hope to others. Whenever you need to poke a button or such on a GUI, you can just make calls to this UDF and instruct it how long to wait, 0 is forever, anyway, let the code to the explaining. Feel free to help expand this UDF. I plan to create new ones as I go along that support all the Win32 and .NET Controls. Ultimately, I would like to be able to fully control any type of control, this works well with most. Just an example of what you can do.
      NOTE: Logger Author(s) .....: Michael Mims (zorphnog)
      ;                    the logging script can be obtained here
      ;                   https://www.autoitscript.com/forum/topic/156196-log4a-a-logging-udf/
       
       
       
       
       
       
       
      WaitForControls.au3 log4a.au3
    • By NassauSky
      Hi All,
      I think I'm so close to solving an automation problem but need that last bit of help. Anyone familiar with automation might know this answer.  The beginning of this code is a nice example from @IanN1990 which I dug into a little and found it's counting my tabs correctly in Chrome.  How may I print out each tab name (probably some sort of property in the automation object)
      #include "CUIAutomation2.au3" ; Window handle Local $hWindow = WinGetHandle( "[CLASS:Chrome_WidgetWin_1]" ) If Not IsHWnd( $hWindow ) Then Return ConsoleWrite( "$hWindow ERR" & @CRLF ) ConsoleWrite( "$hWindow OK" & @CRLF ) ; Activate window WinActivate( $hWindow ) Sleep( 100 ) ; UI Automation object Local $oUIAutomation = ObjCreateInterface( $sCLSID_CUIAutomation, $sIID_IUIAutomation, $dtagIUIAutomation ) If Not IsObj( $oUIAutomation ) Then Return ConsoleWrite( "$oUIAutomation ERR" & @CRLF ) ConsoleWrite( "$oUIAutomation OK" & @CRLF ) ; Desktop element Local $pDesktop, $oDesktop $oUIAutomation.GetRootElement( $pDesktop ) $oDesktop = ObjCreateInterface( $pDesktop, $sIID_IUIAutomationElement, $dtagIUIAutomationElement ) If Not IsObj( $oDesktop ) Then Return ConsoleWrite( "$oDesktop ERR" & @CRLF ) ConsoleWrite( "$oDesktop OK" & @CRLF ) ; Chrome window Local $pCondition $oUIAutomation.CreatePropertyCondition( $UIA_ClassNamePropertyId, "Chrome_WidgetWin_1", $pCondition ) If Not $pCondition Then Return ConsoleWrite( "$pCondition ERR" & @CRLF ) ConsoleWrite( "$pCondition OK" & @CRLF ) Local $pChrome, $oChrome $oDesktop.FindFirst( $TreeScope_Descendants, $pCondition, $pChrome ) $oChrome = ObjCreateInterface( $pChrome, $sIID_IUIAutomationElement, $dtagIUIAutomationElement ) If Not IsObj( $oChrome ) Then Return ConsoleWrite( "$oChrome ERR" & @CRLF ) ConsoleWrite( "$oChrome OK" & @CRLF ) ; Tab item Local $pCondition1 $oUIAutomation.CreatePropertyCondition( $UIA_ControlTypePropertyId, $UIA_TabItemControlTypeId, $pCondition1 ) If Not $pCondition1 Then Return ConsoleWrite( "$pCondition1 ERR" & @CRLF ) ConsoleWrite( "$pCondition1 OK" & @CRLF ) ;~ Find All tab items Local $pTabs, $oUIElementArray, $iElements, $pFound, $oFound, $value $oChrome.FindAll( $TreeScope_Descendants, $pCondition1, $pTabs ) $oUIElementArray = ObjCreateInterface($pTabs, $sIID_IUIAutomationElementArray, $dtagIUIAutomationElementArray) $oUIElementArray.Length( $iElements ) ConsoleWrite( "$iElements:" & $iElements & @CRLF ) For $i = 0 To $iElements - 1 Local $pFound $oUIElementArray.GetElement($i, $pFound) ConsoleWrite($pFound & @CRLF) $pFound.GetCurrentPropertyValue($UIA_NamePropertyId,$value) ;<==PROBLEM HERE ConsoleWrite($value & @CRLF) Next  
      Thanks for any direction.
      🙂
×
×
  • Create New...