applescript play random sound when pressing cmd + enter
I'm looking to play a random sound开发者_如何学JAVA from a set of sound clips in a folder when you press cmd + enter. The applescript will always be running and whenever the user presses cmd + enter a random sound (mp3) will be played without opening iTunes, preferably behind the scenes.
Thanks!
I didn't know about afplay
, but with that, this simple script will do it:
property soundsDirectory : POSIX file "/path/to/sounds/" as alias
tell application "System Events" to ¬
set soundFile to get POSIX path of (some item of soundsDirectory as alias)
do shell script "afplay " & quoted form of soundFile
If you have the classic Mac path of the form Macintosh HD:Users:you:Sounds:
, then you can use property soundsDirectory : alias "Macintosh HD:Users:you:Sounds:"
instead, but either will work. The some item of <list>
command just returns a random item from the list; you have to promise AppleScript that it will be an alias with as alias
so you can get the unix-style path out of it. The quoted form of <text>
command simply puts the text in single quotes (while escaping single quotes) for use in the shell; afplay
just plays it.
For the ⌘↩ requirement, I'd use Spark, although there are a number of options. Spark runs in the background and lets you execute an AppleScript on a keyboard shortcut, among other things. I don't know any way to have the AppleScript always running, but this is fast enough to start up that this shouldn't be an issue. You'll have Spark always running instead.
Download an app called FastScripts and then set a new hot key for cmd + enter and have it launch your AppleScript which plays the random sound.
You could use a script like this to play a random .wav file using QuickTime Player. Edit the path to point to the location (folder) of your sound files. Adjust the delay to allow enough time for the file to play.
tell application "Finder"
set soundFiles to every item of alias "Macintosh HD:sounds" --enter path to folder
set fileCount to count of items in soundFiles
set randomSound to random number from 1 to fileCount
open item randomSound of soundFiles
end tell
tell application "QuickTime Player"
set visible of every window to false
play document 1
delay 20 --adjust to allow for length of sound file
quit
end tell
精彩评论