Jump to content
boomingranny

Start Spotify and play a playlist

Recommended Posts

boomingranny
Posted (edited)
;******************************************************************
;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
aaron832

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

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

  • Similar Content

    • spikespaz
      By spikespaz
      The rule against game automation is misguided and unhelpful for the following reasons.
       
      I am a developer, using AutoIt to automate testing for a game that I am developing. Singleplayer games can be mundane and sometimes cheating can be overlooked. Multiplayer games usually have anticheat against repetitive robotic actions anyways. People want to override the control schemes of games with bad customization. Eg. Axiom Verge, Fortnite (Crouching). Game automation is not always bad. If the user feels the need to automate a singleplayer game for boring or mundane tasks, that is their choice. Similarly, if I wish to use scripts to automate testing, that is my choice.
      Game automation can be a problem for online multiplayer games, giving players a competitive advantage. This could be countered by common sense; ask OP what game they are automating, and is it an online game? What is this script for, and what does it seem to do?

      Please revise the rule as it seems very unnecessary and harmful to people seeking help with innocent attempts at game automation.
    • milkmoron
      By milkmoron
      https://www.autoitscript.com/forum/topic/153520-iuiautomation-ms-framework-automate-chrome-ff-ie/?do=findComment&comment=1156373 At least we have an element title: [Entered By:] class: [WindowsForms10.EDIT.app.0.30495d1_r9_ad1] Having the following values for all properties: Title is: <Entered By:> Class := <WindowsForms10.EDIT.app.0.30495d1_r9_ad1> controltype:= <UIA_EditControlTypeId> ,<50004> , (0000C354) 322;370;736;184 *** Parent Information top down *** 3: Title is: <View Activity> Class := <WindowsForms10.Window.8.app.0.30495d1_r9_ad1> controltype:= <UIA_WindowControlTypeId> ,<50032> , (0000C370) 306;72;784;605 "Title:=View Activity;controltype:=UIA_WindowControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1"" 2: Title is: <> Class := <WindowsForms10.Window.8.app.0.30495d1_r9_ad1> controltype:= <UIA_PaneControlTypeId> ,<50033> , (0000C371) 314;103;768;542 "Title:=;controltype:=UIA_PaneControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1"" 1: Title is: <> Class := <WindowsForms10.Window.8.app.0.30495d1_r9_ad1> controltype:= <UIA_PaneControlTypeId> ,<50033> , (0000C371) 314;103;749;451 "Title:=;controltype:=UIA_PaneControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1"" 0: Title is: <Delete> Class := <WindowsForms10.Window.8.app.0.30495d1_r9_ad1> controltype:= <UIA_PaneControlTypeId> ,<50033> , (0000C371) 314;122;749;432 "Title:=Delete;controltype:=UIA_PaneControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1"" ;~ *** Standard code maintainable *** #include "UIAWrappers.au3" AutoItSetOption("MustDeclareVars", 1) _UIA_setVar("oP1","Title:=View Activity;controltype:=UIA_WindowControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1") ;View Activity _UIA_setVar("oP2","Title:=;controltype:=UIA_PaneControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1") ; _UIA_setVar("oP3","Title:=;controltype:=UIA_PaneControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1") ; _UIA_setVar("oP4","Title:=Delete;controltype:=UIA_PaneControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1") ;Delete _UIA_setVar("EnteredBy:.mainwindow","title:=Entered By:;classname:=WindowsForms10.EDIT.app.0.30495d1_r9_ad1") ;~ Actions split away from logical/technical definition above can come from configfiles ;~_UIA_Action("oP1","highlight") _UIA_Action("oP1","setfocus") ;~_UIA_Action("oP2","highlight") _UIA_Action("oP2","setfocus") ;~_UIA_Action("oP3","highlight") _UIA_Action("oP3","setfocus") ;~_UIA_Action("oP4","highlight") _UIA_Action("oP4","setfocus") _UIA_action("EnteredBy:.mainwindow","setfocus") ;~ *** Standard code Flexible*** #include "UIAWrappers.au3" AutoItSetOption("MustDeclareVars", 1) Local $oP3=_UIA_getObjectByFindAll($UIA_oDesktop, "Title:=View Activity;controltype:=UIA_WindowControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1", $treescope_children) _UIA_Action($oP3,"setfocus") Local $oP2=_UIA_getObjectByFindAll($oP3, "Title:=;controltype:=UIA_PaneControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1", $treescope_children) _UIA_Action($oP2,"setfocus") Local $oP1=_UIA_getObjectByFindAll($oP2, "Title:=;controltype:=UIA_PaneControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1", $treescope_children) _UIA_Action($oP1,"setfocus") Local $oP0=_UIA_getObjectByFindAll($oP1, "Title:=Delete;controltype:=UIA_PaneControlTypeId;class:=WindowsForms10.Window.8.app.0.30495d1_r9_ad1", $treescope_children) _UIA_Action($oP0,"setfocus") _UIA_setVar("EnteredBy:.mainwindow","title:=Entered By:;classname:=WindowsForms10.EDIT.app.0.30495d1_r9_ad1") _UIA_action("EnteredBy:.mainwindow","setfocus") Need some help selecting this defining it as a variable to save and then insert the text within, to the same application but different account.
    • TheSaint
      By TheSaint
      TeraCopy Timer - A program of mine, front end really, that I have been working on (on & off) for some time, but not shared here before, that I recall. Third party program TeraCopy is required.
      Many of you will be familiar with TeraCopy, and it has been discussed here at AF on several occasions, in various sub forums, including Chat.
      BE ADVISED - I still use an older version of TeraCopy (v2.27), a goody but an oldy, so have only tested my program with that. It may work with the newer v3.xx, or may be easily adjusted to do so, but I have not yet gone that route. Likewise, I only use it with Win 7 and Win XP, but I don't imagine there should be any issues with newer Windows. Add to that, my program being devised and created in AutoIt v3.3.0.0.
      So what is TeraCopy Timer and why might you need it?
      --------------------------------------------------------------------------------------
      Those familiar with TeraCopy use, know you can run multiple copy or move jobs either simultaneously or concurrently (one immediately after another has finished). With the free version at least, you have no control over precise order or timing, and no way to deal (without manual interaction) with the pesky Thumbs.db files in Win XP. TeraCopy Timer allows you to do all those things, and in a batch fashion.
      --------------------------------------------------------------------------------------
      Some screenshots and brief explanation
      Main Window
      Minimalist Window
      This new WAIT feature is the simplest and best way to use the program generally (in my view) ... but check out the following, as it is not always the case.
      Advanced Delay Window
      WARNING - It should go without saying, that you take all the usual precautions. For instance, don't use move with the only copy you have of precious files. BACKUP BACKUP BACKUP! Don't hold me liable for anything, except for being a nice guy who likes to share.
      TeraCopy Timer v2.8.zip  (see detail at Post #34)
      TeraCopy Timer v2.9.zip  (see detail at Post #35)
      Enjoy!
      OLDER DOWNLOADS
      P.S. I am not affiliated in any way with those who created and provide the excellent third party program - TeraCopy.
    • Earthshine
      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.
       
      The test installs and can uninstall 7-Zip 15.14 (x64) Setup.exe
      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
      install_7zip_test.au3
    • rcmaehl
      By rcmaehl
      A UDF to connect and control Cisco Finesse on the Local Network via it's provided HTTP API
       
      Current Features:
      Heavyweight
      * Large feature set, containing most Finesse Desktop API functions  
      PLANNED Features:
      Heavyweight
      * Control over own Status as well as Supervisor functionality
        Helpful Premade Examples Files
      * Examples for almost every function
      * Premade CUI and GUI clients showing 
        Ready for all users, beginner and up
      * Detailed Error Reporting to help pin-point problems
      * Thorough parameter checking to prevent accidental script crashes
×