I'm trying to create an AppleScript that uses afplay (as suggested here) to play a random sound file that's located in a directory within the same directory as the script.
folder
-- applescript.scpt
-- sounds
----- sound-x.aiff
I found this comment regarding relative paths to be potentially useful:
 (POSIX path of (path to me))
However, I keep receiving errors when I try mashing it up with this approach for randomness...
set theNumber to 3
set theFiles to {}
repeat
    set file_path to quoted form of (POSIX path of (path to me))
    tell application "Finder" to set aFile to (some file of file_path & "/sounds_dir") as text
    if aFile is not in theFiles then
        set end of theFiles to aFile
        tell application "Finder" to open file aFile
        do shell script ("afplay " & file_path & " > /dev/null 2>&1 &")
    end if
    if (count of theFiles) is equal to theNumber then exit repeat
end repeat
				
                        
In a
script,path to mereturns thepathto thescript filebut we need itsparent pathto add asub path.To compose the correct path, we can use the subroutine
composeFilePath(fileName).The main action is in the repeat loop. I also added a
delayso it's easier to test. Save the script before using sincepath to mewill return a wrong path when its unsaved.