Do we need iTunes or Music to shuffle a sound to play… I do not think so.
Here is my approach…
You need to save the Script as applet and make sure its running. (stay open) You also need to have m4a files in the music folder. But its easy to change to other format and directory. When the applet is running move the mouse to top right corner of the screen and wait 5 seconds. The idle handler will execute activateRandomSoundFromMouseEvent().
It play flac if that is your format, the dialog could be updated with random button to play
next random sound. And when the sound quit you use the mouse in top right corner to start
the dialog again.
use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "GameplayKit"
use scripting additions
-- Set the path to your music library
set thePath to POSIX path of (path to music folder)
-- We search for files with extension m4a it will return a list
set theListOfPaths to my searchByExtension:"m4a" inPath:thePath
-- Shuffle the array and return the first object.
set theRandomFirstObject to my shufflingObjectsInArray:theListOfPaths
on idle
my activateRandomSoundFromMouseEvent()
return 5
end idle
on playSoundWithFile:thePath
set theSound to current application's NSSound's alloc()'s initWithContentsOfFile:thePath byReference:true
theSound's play()
end playSoundWithFile:
on shufflingObjectsInArray:anArray
set randomSource to current application's GKRandomSource's alloc()'s init()
set anArray to current application's NSArray's arrayWithArray:anArray
set shuffle to randomSource's arrayByShufflingObjectsInArray:anArray
set randomObject to (shuffle's objectAtIndex:0) as text
end shufflingObjectsInArray:
on searchByExtension:theExt inPath:thePath
set manager to current application's NSFileManager's defaultManager()
set enumerator to manager's enumeratorAtPath:thePath
set theItems to enumerator's allObjects()
set theList to {}
repeat with i from 1 to (count theItems)
if (((item i of theItems)'s pathExtension)'s isEqualToString:theExt) then
set theItem to thePath & (item i of theItems) as text
set the end of theList to theItem
end if
end repeat
return theList
end searchByExtension:inPath:
on activateRandomSoundFromMouseEvent()
-- Get the Screen size
set screens to current application's NSScreen's screens
set theScreen to (screens's objectAtIndex:0)'s frame() -- main screen
set {{x, y}, {width, height}} to {item 1 of theScreen, item 2 of theScreen}
-- Get the mouse location
set theLoc to current application's NSEvent's mouseLocation()
if ((theLoc's x as integer) > (width - 10) as integer) and ((theLoc's y as integer) ≥ (height - 10) as integer) as boolean then
my playSoundWithFile:(my theRandomFirstObject)
else
return 0
end if
set theQuit to display dialog "This dialog will quit the random sound..." buttons {"Quit"}
if (theQuit's button returned) is "Quit" then
quit me
end if
end activateRandomSoundFromMouseEvent