hi @raymondca,
Nice idea and good scripts. I hope I'm not overstepping, but I was inspired to fix the issue with the second script, which uses a method that brings Chrome into the foreground and flicks through the tabs in order to send the spacebar keystroke. It is very distracting, although a necessary evil to maintain the generality of your script, which I see you've written to make it easily adaptable to use with other music sites besides Youtube Music.
If, like me, however, you primarily use YouTube Music anyway, then I wrote a site-specific script that will Play/Pause it without the need to shift application focus or change active tabs. It utilises in-browser JavaScript, so View > Developer > Allow JavaScript From Apple Events will need to be ticked to allow AppleScript to send JS commands to Chrome.
Play/Pause Action Script:
use Chrome : application "Google Chrome"
property URL : "music.youtube.com"
property _W : a reference to every window of Chrome
property _T : a reference to every tab of _W
property tab : a reference to (_T where its URL contains my URL)
property js : "document.querySelector('.play-pause-button').click()"
if Chrome is not running then return
if the number of _W = 0 or the number of my tab = 0 then return
repeat with T in the contents of my tab
execute of T javascript js
end repeat
After I did that, I decided to do a similar re-write of your main script as well, because I noticed that, if more than one YouTube Music tab is open, the order in which they exist determines which tab's title is returned, even if it's the title of a tab that isn't currently playing any music. The fix was simple enough, which was to do a quick check to make sure the tab's title wasn't simply "YouTube Music"
.
Song Title Main Script:
use Chrome : application "Google Chrome"
property URL : "music.youtube.com"
property _W : a reference to every window of Chrome
property _T : a reference to every tab of _W
property tab : a reference to (_T where its URL contains my URL)
property text item delimiters : {null, " - YouTube Music", "YouTube Music"}
if Chrome is not running then return
if the number of _W = 0 or the number of my tab = 0 then return
repeat with T in my tab's contents
set tt to T's title
if "YouTube Music" ≠ tt then exit repeat
end repeat
return tt's text items as text
Again, like the first script, this one is fairly specific to YouTube Music, although much easier to adapt to other sites than the first. Hope you and/or other users find one or both of these useful.