AppleScriptObjC: Can't create AVMIDIPlayer object - applescript

I'm having some trouble with a bit of AppleScript ObjC code. The problem line seems to be when I initialize the AVMIDIPlayer object (3rd line of repeat). It comes back with a -1 error, (AVAudioEngineManualRenderingStatusError). The next line then fails, because a Nil object doesn't have any methods.
Here's the relevant bits:
property NSURL : a reference to current application's NSURL
property AVMIDIPlayer : a reference to current application's AVMIDIPlayer
on open (filelist)
repeat with each_item in filelist
set myfile to quoted form of POSIX path of each_item as string
set myMIDIFile to (NSURL's fileURLWithPath:myfile)
set {myMIDIPlayer, theError} to (AVMIDIPlayer's alloc()'s initWithContentsOfURL:myMIDIFile soundBankURL:none |error|:(reference))
myMIDIPlayer's prepareToPlay()
myMIDIPlayer's play(myHandler)

The reason of the issue is quoted form of.
Use it only in do shell script lines to escape string containing spaces and special characters, nowhere else.
set myfile to POSIX path of each_item -- no coercion: POSIX path is string
And handle theError 😉

Related

Applescript to find the newest folder

I'm trying to find the folder which has been last modified. (Actually, I'm only interested in that folder and not an ordered list.) I'm getting an -10010 error.
tell application "Finder"
try
set latestFolder to item 1 of (sort (get name of folders of folder ("/Users/c64/Desktop" as POSIX file)) by creation date) as alias
set folderName to latestFolder's name
end try
end tell
If you're looking for the name of the last modified folder on the Desktop, then this will do it:
tell application "Finder"
set latestModifiedFolderName to name of item 1 of (sort every folder by modification date)
end tell
By the way, the AppleScript Dictionary for Finder does not contain terms POSIX file or POSIX path and when using e.g. POSIX file inside of a tell application "Finder" block, Finder will throw a non-fatal error if it can be coerced into an alias, otherwise it can throw a fatal error. That said, if you are dealing with a POSIX path, it's probably best to pass it to Finder as an alias, and I'd recommend coercing the POSIX path to an alias before passing it to Finder, e.g.:
set thisFolderPath to POSIX file "/Path/To/Some/Folder" as alias
tell application "Finder"
set latestModifiedFolderName to name of item 1 of (sort every folder of thisFolderPath by modification date)
end tell
Note: The example AppleScript code above is just that, and does not include any error handling as may be appropriate/needed/wanted, the onus is upon the user to add any error handling for any example code presented and or code written by the oneself.

Using Applescript to open filenames with escaped characters

Once upon a time, it was possible to put file:// urls into webpages, and if that URL matched a file on your desktop, why, the file would open on your computer when you clicked on the link.
This functionality has been disabled for security reasons, but I'm trying to recreate it for my own personal use. I'm trying to use a custom URL protocol and an Applescript application as described at http://www.macosxautomation.com/applescript/linktrigger/. I've almost got it working, with one difficulty: A URL can't have spaces in it, so they get escaped, as do other special characters like "&". How can I convince Applescript to open a file with a path with escaped characters in it, such as "/Users/jim/Dropbox/Getting%20Started.pdf"?
tell application "Finder"
open "/Users/jim/Dropbox/Getting Started.pdf" as POSIX file
works fine, whereas
tell application "Finder"
open "/Users/jim/Dropbox/Getting%20Started.pdf" as POSIX file
fails.
Is there an easy (i.e. non-regex) way to make this work?
You can use the open command in do shell script.
Like this:
set tUrl to "/Users/jim/Dropbox/Getting%20Started.pdf"
do shell script "open 'file://" & tUrl & "'"
Try the following:
tell application "Finder"
open my decodeFromUri("/Users/jim/Dropbox/Getting%20Started.pdf") as POSIX file
end tell
after declaring the following handler:
(*
Decodes a string previously encoded for inclusion in a URI (URL).
Note: Uses Perl and its URI::Escape module (preinstalled as of at least OSX 10.8).
Adapted, with gratitude, from http://applescript.bratis-lover.net/library/url/
Example:
my decodeFromUri("me%2Fyou%20%26%20Mot%C3%B6rhead") # -> "me/you & Motörhead"
*)
on decodeFromUri(str)
if str is missing value or str = "" then return str
try
# !! We MUST use `-ne` with `print` rather than just `-pe`; the latter returns the input unmodified.
return do shell script "printf '%s' " & quoted form of str & " | perl -MURI::Escape -ne 'print uri_unescape($_)'"
on error eMsg number eNum
error "Decoding from URI failed: " & eMsg number eNum
end try
end decodeFromUri

Embed a bash shell script in an AppleScriptObjC application with Xcode

I have attempted to follow the instructions on this post but I am falling short of understanding how some of the posters instructions work.
I want to be able to package the app with a prewritten bash script and then execute it, but don't follow from Step 4 onwards.
Post writes:
4. Also in your AppleScriptObjC script, add the following where appropriate:
property pathToResources : "NSString" -- works if added before script command
5. Where appropriate, also add the following in your AppleScriptObjC script:
set yourScript to pathToResources & "/yourScriptFile.sh"
-- gives the complete unix path
-- if needed, you can convert this to the Apple style path:
set yourScriptPath to (((yourScript as text) as POSIX file) as alias)`
6. As an aside, you could then open the file for read using
tell application "Finder"
open yourScriptPath
end tell
Questions:
Where do I add the line:
property pathToResources : "NSString"
Do I add which of the following, and where?
set yourScript to pathToResources & "/yourScriptFile.sh"
OR
set yourScriptPath to (((yourScript as text) as POSIX file) as alias)
How is it possible to execute the script itself? The mention As an aside, you could then open the file for read using only covers the Apple style path, it does not cover using the aforementioned style.
Can anyone shed a bit more light on this for me, or post a static copy of a AppDelegate.applescript file that shows how the original poster required the base code to be used? I have tried his method and looked across the internet for the past 3 weeks to no avail. I don't want to have to convert all my code for specific tools from bash scripts into AppleScript, as this would take a lot of work.
I only need to know how to reference to the script file (for example myBashScript.sh) in my app, which would reside in the application and be included by Xcode at time of compilation.
I think you should use the command path to resource <specifiedResource>.
See Standard Additions, path to resource.
You could set it by set myVariableName to path to resource "myBashScript.sh" or just use the command instead of your property so it points always to the right place (a user could move your app while running... lol).
ADDITION:
I did it that way in my AppleScript-Application:
on run_scriptfile(this_scriptfile)
try
set the script_file to path to resource this_scriptfile
return (run script script_file)
end try
return false
end run_scriptfile
Whenever I want to run a script that is bundled within my app I do this:
if my run_scriptfile("TestScript.scpt") is false then error number -128
run_scriptfile(this_scriptfile) returns true when everything worked.
I ended up bringing all the information together and now have a solution.
This takes into consideration the following facts:
firstScript = variable name that points to a script called scriptNumberOne.sh
scriptNumberOne.sh = the script that I have embedded into my application to run
ButtonHandlerRunScript_ = the name of the Received Action in Xcode
pathToResources = variable that points to the internal Resources folder of my application, regardless of it's current location
Using this information, below is a copy of a vanilla AppDelegate.applescript in my AppleScriptObjC Xcode project:
script AppDelegate
property parent : class "NSObject"
property pathToResources : "NSString"
on applicationWillFinishLaunching_(aNotification)
set pathToResources to (current application's class "NSBundle"'s mainBundle()'s resourcePath()) as string
end applicationWillFinishLaunching_
on ButtonHandlerRunScript_(sender)
set firstScript to pathToResources & "/scriptNumberOne.sh"
do shell script firstScript
end ButtonHandlerRunScript_
on applicationShouldTerminate_(sender)
-- Insert code here to do any housekeeping before your application quits
return current application's NSTerminateNow
end applicationShouldTerminate_
end script

Updating script to find a new type of file

I need to update the script shown below to find a new file type and naming system and have no idea what I'm doing. It use to pull a file named DQXXXXX1.eps and placed in the listed location. The new files are XXXXX_random.pdf. The random in the file name is several series of numbers that change for each file. The important numbers are the first 5, I would like the script to pull all files in that initial location and place into the other location.
The current script is:
set DQfolder to alias "Prepress:ArtFiles:00-Logos A to Z:1-DQ:"
tell application "Finder"
display dialog "enter number" default answer ""
set theNum to text returned of result as string
--try
move alias (DQfolder & "DQ" & theNum & ".eps" as string) to "Macintosh HD:__DQ Incoming:" with replacing
--on error {}
--move alias (DQfolder & "DQ" & theNum & ".tif") to "Macintosh HD:__DQ Incoming:" with replacing
--end try
end tell
Try your script like the following. You have a few things that need to be fixed...
Basically you are adding the strings wrong. You need to first coerce DQfolder to a string before you can add the other strings to it. The way you are doing it can't work because DQfolder is an alias so you can't add other strings to it until you coerce the alias to a string.
the folder path in your command has to be an alias-type file or a folder specification. As such you need to put the word "alias" or "folder" in front of it. A string path will not work. Applescript rarely works with string paths.
"display dialog" is not a Finder command and as such you don't need to put it in the Finder block of code.
"text returned" from your display dialog command is already "text" so you do not need to coerce it to a string. That's why it's called "text" returned... even if you entered a number it's class is still text.
Of course I can't check this code because I don't have files at those paths, but it should work. Good luck...
set DQfolder to alias "Prepress:ArtFiles:00-Logos A to Z:1-DQ:"
display dialog "enter number" default answer ""
set theNum to text returned of result
tell application "Finder"
move alias ((DQfolder as text) & "DQ" & theNum & ".eps") to alias "Macintosh HD:__DQ Incoming:" with replacing
end tell

list subfolders using applescript

This is my first applescript. I thought I'd do something simple like navigating to a folder using a path and listing the subfolders...Unfortunately, I can't figure it out :-)
Here is what I've tried so far:
The first try:
tell application "Finder"
set the_folder to POSIX path of "Users:MyName:Doc"
log the_folder
set folder_list to every item of folder the_folder
log folder_list
end tell
This produces an error:
"Finder got an error: Can't get folder "/Users/MyName/Doc".
Could someone please:
1. Explain to me what I'm doing wrong.
2. Provide an example that works.
Thanks in advance.
btw the folder does exist on my machine...
UPDATE: Oops! It appears that I have given you the wrong information so I will give you the correct information.
The command POSIX path of requires a complete alias reference. By that I mean supplying the full file reference (i.e. <your_disk_name>:Users:<your_user_name>:somefolder:). Make sure that if you're referring to a folder that you end the reference with a colon (i.e. Macintosh HD:Users:). An improved version would look like this:
tell application "Finder"
set the_folder to (POSIX path of ("<your_disk_name>:Users:<your_user_name>:Doc:") as alias) as alias
set folder_list to every item of the_folder
end tell
OPTIONAL
To coerce a POSIX path (i.e. /Users/<your_user_name>/somefolder) back into an alias, two conversions are needed.
Conversion 1: The first step is to convert the reference into a file reference. To do this, place the words as POSIX file after the reference, like so:
"/Users/<your_user_name>/somefolder" as POSIX file
This code procudes a file reference in this form: file "<your_disk_name>:Users:<your_user_name>:somefolder:"
Conversion 2: Add a second coercion, as alias, to the end of the reference...
"/Users/<your_user_name>/somefolder" as POSIX file as alias
This code produces an actual alias reference: alias "<your_disk_name>:Users:<your_user_name>:somefolder:
If you have any questions, just ask. :)
Posix paths are paths you use at the command line and are "/" delimited. Applescript paths are ":" separated so just use those. Try this script to see what the path should look like...
set folderPath to (choose folder) as text

Resources