Scripting Bridge for iTunes

I'm trying to do something simple and efficient with scripting bridge and iTunes, which is to display the number of the track currently playing in the playlist (aka "get index of current track"), so here's my try:
// initialization
iTunes = \[ SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes" \] ;
// repeat this on a timer
iTunesTrack* currentTrack = \[ iTunes currentTrack \] ;
iTunesPlaylist* currentPlaylist = \[ iTunes currentPlaylist \] ;
SBElementArray* currentTracks = \[ currentPlaylist tracks \] ;
NSInteger index = \[ currentTracks indexOfObject: currentTrack \] ;
but this doesn't work because currentTracks and currentTrack are references that haven't been evaluated (and indexOf doesn't persuade them to evaluate). This can be fixed by:
NSInteger index = \[ \[ currentTracks get \] indexOfObject: \[ currentTrack get \] \] ; // leaks mem!
and while the index is now correct, this leaks memory (about 1K bytes per call - alot more after some time!). Am I doing something wrong? Does Scripting Bridge have a memory leak? Is there a better way to get this index, or am I stuck going back to AppleScript (I promised myself I'd quit if it got messy). Thx, -L.

Thanks again for your collective guidance - per your advice, I've tried allocating and releasing an autorelease pool every get/loop. In fact, I've tried many variations of draining and releasing pools, as well as variable assignments and releases. No change in the memory leak.
I'm starting to suspect that the leak is lower-level than anything Objective-C is doing, but please correct me!
I've distilled the problem into just a few lines of code inserted into the generic Cocoa app template generated by Xcode. Please take a look below and see how one might change it to not leak memory - Activity Monitor says it ticks up .01MB (about 10K) in RSS memory usage every few seconds.
Thanks for your continued guidance, -Lance.
// generated a skeletal Cocoa app (just removed generic copyright comments, added startTrackWatcher)
// generate iTunes.h with sdef /Applications/iTunes.app | sdp -fh --basename iTunes
// and add ScriptingBridge framework to project
#import <Cocoa/Cocoa.h>
int main(int argc, char *argv[])
void startTrackWatcher() ; // added these two lines
startTrackWatcher() ; // for watching mem leak
return NSApplicationMain(argc, (const char **) argv);
// added lines below for startTrackWatcher
#import <ScriptingBridge/ScriptingBridge.h>
#import "iTunes.h"
@interface Status : NSObject {
@public
NSTimer* timer ;
iTunesApplication* iTunes ;
- (void)doit:(NSTimer*)timer;
- (Status*)initWithTime:(int)time;
@end
@implementation Status
- (void)doit:(NSTimer*)t
// NSAutoreleasePool* pool = [[ NSAutoreleasePool alloc ] init ] ;
iTunesTrack* currentTrack = [ iTunes currentTrack ] ;
iTunesPlaylist* currentPlaylist = [ iTunes currentPlaylist ] ;
SBElementArray* currentTracks = [ currentPlaylist tracks ] ;
// NSInteger index = [ currentTracks indexOfObject: currentTrack ] ; // wrong because items aren't evaluated
NSInteger index = [ [ currentTracks get ] indexOfObject: [ currentTrack get ] ] ; // leaks memory (check Activity monitor)!
printf( "%d
", index ) ;
// [ pool drain ] ;
// [ pool release ] ;
- (Status*)initWithTime:(int)time {
/NSAutoreleasePool pool =*/ [[NSAutoreleasePool alloc] init];
timer = [NSTimer scheduledTimerWithTimeInterval:time
target:self
selector:@selector(doit:)
userInfo:timer
repeats:YES] ;
iTunes = [ SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes" ] ;
return self ;
@end
void startTrackWatcher() {
[[ Status alloc ] initWithTime:0.1 ] ;

Similar Messages

  • Scripting Bridge and iTunes

    I'm trying to add a playlist to iTunes via some Obj-C code. (Yeah I know AppleScript would be simpler, but part of this is for me to learn coding with Cocoa.) I'm not new to coding, just the Mac flavor of it, and I suspect I'm missing something simple. Anyway, the procedure in question (from a button's click handler):
    <pre>
    iTunesApplication *iTApp;
    SBElementArray *thePlaylists;
    NSDictionary *newPlaylistProps;
    iTunesPlaylist *newPlaylist;
    iTApp = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
    if ([iTApp isRunning]) {
    thePlaylists = [(iTunesSource*)[[iTApp sources] objectAtIndex:0] playlists];
    newPlaylistProps = [NSDictionary dictionaryWithObject:@"foobar" forKey:@"name"];
    newPlaylist = (iTunesPlaylist*)[[[iTApp classForScriptingClass:@"playlist"] alloc] initWithProperties:newPlaylistProps];
    [thePlaylists addObject:newPlaylist];
    </pre>
    I've got iTunes.h created and #imported like the ADC guide showed. The code above works fine until the addObject call, at which point I get an Apple event error -10014. This seems to mean I sent in a list when the handler wanted a single object. I thought newPlaylist counted as just an object.
    Also regarding populating the thePlaylists var - I've resorted to grabbing the first source solely to simplify things. Until I hit this wall, I was iterating the sources to find the library one.
    Any help would be appreciated - thanks!

    Short answer: Scripting Bridge's design is flawed. See the 'jumpstart me with the scripting bridge' thread over on AppleScript-implementors for an explanation of this particular defect:
    http://lists.apple.com/archives/Applescript-implementors/2007/Nov/index.html
    Your options are:
    1. Work around Scripting Bridge's brokenness by sending your own 'make' Apple event via -[SBObject sendEvent:id:parameters:]. (Or even via AEBuildAppleEvent or NSAppleEventDescriptor and AESendMessage if you're particularly masochistic.) You'll need to know the raw AE codes for the 'make' command to do this; e.g. Script Editor can save an application's dictionary to .sdef (XML) file, or ASDictionary [1] can export it in a more readable plain text format.
    2. Use AppleScript via NSAppleScript. Somewhat defeats the purpose of the exercise, but AppleScript knows how to speak Apple events properly so at least you know it'll work.
    3. Use a third-party bridge that speaks Apple events the same way as AppleScript does. For ObjC, use objc-appscript [2]:
    ITApplication *itunes = [[ITApplication alloc] initWithName: @"iTunes.app"];
    NSDictionary *properties = [NSDictionary dictionaryWithObject:@"my playlist" forKey:[ASConstant name]];
    ITMakeCommand *cmd = [[[itunes make] new_: [ITConstant playlist]]
    withProperties: properties];
    ITReference *playlist = [cmd send];
    [itunes release];
    HTH
    [1] http://appscript.sourceforge.net/download.html
    [2] http://appscript.sourceforge.net/objc-appscript.html

  • "Delete Selected Track Files" Applescript script fails for iTunes 7

    The Delete Selected Track Files script, which is found on the Apple site http://www.apple.com/applescript/itunes/, fails with a error message of "iTunes got an error: file track id 42130 of user playlist id 30791 of source id 40 doesn't understand the delete message." The message is the same regardless of which song(s) I try to delete. Does anyone know how to update the script or know of a workaround?

    Found my mistake. I was testing the script by playing a track from a shared iTunes library across my local net. As soon as I played a track residing on the local machine itself the script worked in iTunes 8.0 as it worked before on iTunes 7.x
    Apparently I'll need to code for the case of a shared track in order to correctly resolve the alias to the file track on the remote machine.
    Thanks Niel!

  • Scripting Bridge for Color Management

    Hi,
    I need a script that instruct Bridge to Switch to a color Preset.
    I have no problem using AS but Dictionary os Bridge don't have support to AS but only can invoke Javascript.
    Somebody has an example about how to set Bridge (and Sync automatically all other Adobe APP) choosing a Color Preset name?
    Stefano

    I have looked at this before now and JavaScript does not have access to that app preference… It would have been handy IMO did not see it added to CS5 either…

  • Compiling code generated for Scripting Bridge

    Hi,
    I have generated code for iTunes on MAC OS X leopard, I added the generated header file in my project, and imported (#import "Itunes.h") in my implementation file of Objective 'C'. I also linked my project with Scripting Bridge. (/System/Library/Frameworks/ScriptingBridge.framework.)
    But when I build my project I get following error,
    "error ScriptingBridge/ScriptingBridge.h no such file or directory".
    MY project link with other framework, cocoa, AppKit, WebKit fine, and it has been working fine as a web kit plug-in.
    I am new to MAC and Objective 'C' programming, could some one help solve this problem.
    Thanks,
    kumar
    Sample Code from I Tunes.h
    ++++++++++++++++++++++++++++
    #import <AppKit/AppKit.h>
    #import <ScriptingBridge/ScriptingBridge.h>
    @class ITunesPrintSettings, ITunesApplication, ITunesItem, ITunesArtwork, ITunesEncoder, ITunesEQPreset, ITunesPlaylist, ITunesAudioCDPlaylist, ITunesDevicePlaylist, ITunesLibraryPlaylist, ITunesRadioTunerPlaylist, ITunesSource, ITunesTrack, ITunesAudioCDTrack, ITunesDeviceTrack, ITunesFileTrack, ITunesSharedTrack, ITunesURLTrack, ITunesUserPlaylist, ITunesFolderPlaylist, ITunesVisual, ITunesWindow, ITunesBrowserWindow, ITunesEQWindow, ITunesPlaylistWindow;
    typedef enum {
    ITunesEKndTrackListing = 'kTrk' /* a basic listing of tracks within a playlist */,
    ITunesEKndAlbumListing = 'kAlb' /* a listing of a playlist grouped by album */,
    ITunesEKndCdInsert = 'kCDi' /* a printout of the playlist for jewel case inserts */
    } ITunesEKnd;
    typedef enum {
    ITunesEnumStandard = 'lwst' /* Standard PostScript error handling */,
    ITunesEnumDetailed = 'lwdt' /* print a detailed report of PostScript errors */
    } ITunesEnum;

    Hi,
    Could you provide some more details on the entity bean? Like, part of ejb-jar,the implementation code?
    Does your bean use any field by name 'dirty'?
    There was some discussion on a similar problem here - http://forums.oracle.com/forums/message.jsp?id=906659
    Hope this helps,
    Neelesh
    OTN Team @IDC

  • Scripting Bridge & iTunes?

    Hi, has anyone gotten very far into using Scripting Bridge on Leopard with Python and iTunes? I tried, but got stuck pretty fast. I'm trying to iterate over tracks and (among other things) find out what their file names are.
    from ScriptingBridge import *
    itunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
    lib = itunes.sources()[0].playlists()[0]
    tracks = lib.tracks()
    print tracks[0].location
    This works up until the last line, but then complains "AttributeError: 'ITunesTrack' object has no attribute 'location'". So I thought I would try to ask for a list of "file tracks" instead of "tracks", because that's how appscript seems to work, but no luck.
    from ScriptingBridge import *
    itunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
    lib = itunes.sources()[0].playlists()[0]
    tracks = lib.file_tracks()
    print tracks[0].location
    produces "AttributeError: 'ITunesPlaylist' object has no attribute 'file_tracks'". And then, although I really want to embrace Scripting Bridge, I thought I'd try a last resort and go back to using appscript (that's what I used on Tiger). But that doesn't seem to work on Leopard... while retrieving the list of tracks, it works for a while and then says
    Traceback (most recent call last):
    File "/Library/Python/2.5/site-packages/appscript-0.17.2-py2.5-macosx-10.5-i386.egg/apps
    cript/reference.py", line 372, in _call_
    if e.number in [-600, -609] and self.AS_appdata.path: # event was sent to a local app
    for which we no longer have a valid address (i.e. the application has quit since this aem.
    Application object was made).
    AttributeError: AppData instance has no attribute 'path'
    even though iTunes hasn't quit. Any suggestions? I know I could read & write XML, but I want this to work while iTunes.app is running. This seems like it ought to be a really basic task, but I'm out of ideas. Thanks in advance.
    Message was edited by: dormouse310

    The problem here is that Scripting Bridge is just a bit too arrogant and nit-picky for its own (or its users') good.
    i.e. Unlike appscript, which carefully mimics the way that AppleScript works in order to ensure maximum compatibility with existing applications - all of which have for the last 14 years been designed and tested against AppleScript - Scripting Bridge tries to impose its own particular ideas of how application scripting should operate. The result is that applications which work fine with AppleScript but don't precisely behave in the way that Scripting Bridge thinks they should behave can end up being partially or even completely inaccessible to Scripting Bridge users (at least not without resorting to klunky low-level workarounds).
    (Incidentally, I did caution Apple a year ago about the compatibility problems that the Scripting Bridge-style approach would cause - I made some of the same mistakes myself in early versions of appscript - but unfortunately they went ahead and did it anyway.)
    In this case, it's Scripting Bridge's insistence on enforcing the object model structure defined in iTunes' dictionary that's causing the problem, since iTunes' dictionary is rather inconsistent in declaring the types of elements each class supports. For example, if you look up the 'playlist' class's definition, you'll see that it forgets to list 'file track' as an element. This doesn't bother AppleScript (or appscript), but it trips up the rather less tolerant Scripting Bridge, as you can see here:
    from ScriptingBridge import *
    itunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
    lib = itunes.sources()[0].playlists()[0]
    filetracks = lib.fileTracks() # this line raises an AttributeError: 'ITunesPlaylist' object has no attribute 'fileTracks'
    print filetracks[0].location()
    Not that this excuses the iTunes developers for their sloppy documentation, mind (and you should definitely file a bug report on it), but it isn't much consolation to users who just want to do things that they know worked fine in AppleScript or appscript.
    Anyway, it is possible to work around this particular limitation in Scripting Bridge by resorting to raw AE codes; in this case:
    import struct
    from ScriptingBridge import *
    itunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")
    lib = itunes.sources()[0].playlists()[0]
    filetracks = lib.elementArrayWithCode_(struct.unpack('>L', 'cFlT')[0]) # filetracks = lib.fileTracks()
    print filetracks[0].location()
    To obtain the raw codes, use ASDictionary's plain text export option, Smile's 'copy translate' feature, Script Debugger's advanced dictionary viewer, or save the dictionary as an sdef file in Script Editor. And don't forget to take account of endianness issues when converting four-char-code strings to ints as shown above.
    As for the error you're getting with appscript:
    Appscript identifies local applications by their process numbers, so if you quit and relaunch an application after you've created an 'app' object for it and then use that app object to send the application another command, appscript will deliberately raise an error (-609) to tell you the process number used by that app object is no longer valid. (Note: you should actually get a CommandError, not AttributeError, here - the error message you're actually seeing is caused by a bug in 0.17.2's error handling/reporting code that's since been fixed - but the general explanation still holds.)
    In your case, however, it sounds as if iTunes is running throughout, so that isn't what's causing appscript to error. I suspect the actual cause is a timeout error; unfortunately this gets wrongly reported in appscript as error -609 instead of -1712 (timeout error) as it should be. Obviously, getting the wrong error message when an error occurs is rather confusing for users, and fixing this problem is on my TODO list for the next release, although I've yet to figure out why the Apple Event Manager should be giving appscript the wrong error number in the first place. In the meantime, you should be able to confirm that it's a timeout error by running the equivalent command in AppleScript within a 60 second timeout block (which is, IIRC, the default timeout used by appscript 0.17.2).
    As to why it can take so long to get file tracks in iTunes - I'm not an iTunes guru, but you could try asking on the AppleScript-users mailing list to see if anyone there has any suggestions. As for avoiding timeout errors in the first place, you can increase the timeout delay for your appscript command via its 'timeout' argument (this is equivalent to AS's 'with timeout' block, except that it only affects the command it's used in) - see ch.11 of the appscript manual for details.
    HTH
    has
    (p.s. If you've any questions or problems with Python appscript, best place to post them is the PythonMac-SIG mailing list at python.org, or mail me directly if you prefer.)

  • Button for iTunes scripts and iTunes Plug-Ins is gone in 7.3.x

    In iTunes 7.3.x I am missing the upper button for iTunes scripts and ITunes Plug-Ins for the little add on programs like iTunes-BPM and iTunes-Lame.
    Does anybody know a trick how I get this button to show up again?
    I am talking about this button:
    /___sbsstatic___/migration-images/505/5054148-1.jpg

    No idea why it's not working. Never seen this problem before.
    Only thing I can think of is make sure the name of the Scripts folder is spelled correctly (not an extra space) /usr/library/iTunes/Scripts/.
    Post over here -> AppleScripts for iTunes (Mac)

  • Bridge for Mac without cover arts from iTunes

    Hello,
    I just upraded to Sony Bridge for Mac 3.9 (3903) and since then no cover art from iTunes albums is displayed any more.
    Previous Version of the Bridge had already some difficulties with Cover Art, mainly regarding TIFF-images. But now
    nothing at all is displayed.
    Of course I have restarted the application as well as the Mac itself - no change of the behaviour occured.
    Do I still have any options to try?
    with best regards
    Matthias
    Solved!
    Go to Solution.

    Hello,
    I have mostly MP3-Files in my iTunes library (90%). Even purchased songs are converted to MP3 because of the higher compression, even with 160 kbit/s and VBR. But I think regarding coverart the graphics format is more important. Here native Apple cover art seems to be generally TIFF, which sometimes makes problems with Bridge for Mac, esp. larger images. If I convert those large TIFF-images to JPEG, the problems disappear most of the times.
    And "Yes", I sent a bug report to SONY directly.
    Thank you very much - Matthias

  • Bridge for Mac did not work for itune transfer

    Tried to use Bridge for Mac to transfer itune music to newly purchased xperia z2, but did not work!   Anyone done it successfully?

    Hi Ebmsa,
    Could you please answer the following questions so that I can understand your problem better?
    1. What format were the songs that you were trying to transfer in? .mp3 etc?
    2. Are you connecting your phone in MTP or MSC mode?
    3. How much available memory does your phone have?
    4. What's your phone and build version?
    5. What's your android version, Bridge for Mac version and Mac OSX version?
    Please let me know if you have any questions regarding my questions above.
    Best Regards,
    David

  • Cannot select iTunes videos for sync with Sony Bridge for Mac version 3.6

    Hi,
    I have a Sony xperia T.
    I am running Sony Bridge for Mac version 3.6 (the latest I think)
    I would like to sync a couple of movies to my phone so I can take them with me when travelling, but the itunes library movies are "greyed out" and I cannot select them to enable them to sync.
    I cannot see why.
    Also some of my music is the same - some albums are "greyed out" and cannot be selected.
    Anyone else seen this and worled out the solution ?
    if so - please advise !
    Hewey

    They are probably DRM protected, if so, you wont be able to transfer them 
    "I'd rather be hated for who I am, than loved for who I am not." Kurt Cobain (1967-1994)

  • Trying to create a script for iTunes

    This is one of those questions that probably has a very simple answer unless you haven't worked with Automator or applescripts.
    I found Automator, created a script for iTunes to change settings for audiobooks that I import from CD so that it remembers it's place in a "song", makes it so that it doesn't show up in shuffle lists, and doesn't have a gap between songs. Yippee for me.
    I click on File, Save, name the file and save it and ... it doesn't show up under iTunes. It only took me 45 minutes to get it so that the scroll icon shows up under iTunes (I'm so confused now that I don't even know which thing I did caused that to happen) but my script I created doesn't show up.
    I did find one place that said to place the file in (myname\library\scripts\programname) So I went to my home folder, find the library folder, found the scripts folder, and found only one application under there (Safari) but no iTunes. I created a folder called iTunes and saved my script there but ... it doesn't show up under iTunes.
    I did try quitting iTunes and opening it back up and ... it still isn't there.
    Is this even the right place to ask this question?

    OlsonBW wrote:
    ........Is this even the right place to ask this question?
    If it's not, then may I recommend MacFormat Magazine's own discussions forum -
    http://forum.macformat.co.uk/login.php?redirect=privmsg.php&folder=inbox
    I found that this is full of 'Users' and more likely to be experienced using AppleScript and Automator.
    Although I don't say that someone here won't be able to help. Just might take longer here or, as you yourself suggest, may need posting elsewhere on this site. Just speaking from previous experience of both sites

  • Scripting Bridge: how to set current iTunes playlist

    I know how to get the current iTunes playlist using Scripting Bridge, but how do I set the current playlist?

    This is the answer:
    1. Dig into iTunesApplication's "sources" to find iTunesSource "Library"
    2. Dig into iTunesSource "Library" to find iTunesPlaylist "Party Shuffle"
    3. Do a reveal.

  • Script listener for Bridge?

    Sure would be nice to have a script listener plug-in for the Bridge.
    Is there one available?
    Larry

    Bob,
    It is a plug-in that comes with Photoshop. You can put it in the plug-in folder. In Photoshop CS2 it is "ScriptListener.8li".
    In Photoshop, it generates JavaScript and Visual Basic code whenever you perform a function. The code is written to a log file that
    you can cut and paste into you script. It is a way of getting code for functions that are not included in the JavaScript
    implementation for Photoshop.
    Here is an example of Fit image on screen:
    var id57 = charIDToTypeID( "slct" );
    var desc15 = new ActionDescriptor();
    var id58 = charIDToTypeID( "null" );
    var ref6 = new ActionReference();
    var id59 = charIDToTypeID( "Mn " );
    var id60 = charIDToTypeID( "MnIt" );
    var id61 = charIDToTypeID( "FtOn" );
    ref6.putEnumerated( id59, id60, id61 );
    desc15.putReference( id58, ref6 );
    executeAction( id57, desc15, DialogModes.NO );
    It is very useful in Photoshop. It would be great if it were available in Bridge for the writing of JavaScript scripts.
    Larry

  • How to use AS's "make new" command in Scripting Bridge?

    Anybody know how to rewrite this line of Applescript in Cocoa using the Scripting Bridge?
    tell application "iTunes" to make new playlist with properties {name:"Some Name"}
    I'd hate to have to embed AS into my app just for this thing.
    Is there maybe some page in the documentation on Applescript object allocation in Scripting Bridge that I'm missing?
    Thanks in advance.

    If you have the Time Capsule setup in Bridge Mode as you indicate, the ethernet ports are all equal and they will behave just like a normal ethernet "switch".
    If you've double checked to make sure that you have a good ethernet cable and you don't have a connection at the WAN port, but do on the other LAN ports, unfortunately the WAN port is defective.

  • Problem Running App with Scripting Bridge on MAC OS X TIger

    Hi,
    I have an application which link with Scripting Bridge Frame work, use XCODE 3.0 and SDK 10.5. I use Scripting Bridge, to control some functionality of ITune from Objective-C. This Application run fine on Leopard and behave as expected. When I Run this application on Tiger this does not load.
    Considering that scripting Bridge was first released om Leopard.
    Can my Above Application Run on Tiger. If not how do I interface ITune from Objective-C, on both Tiger and Leopard? IS there update which suppose to fix this?
    Thanks
    Akhilesh

    webdevcda wrote:
    Considering that scripting Bridge was first released om Leopard.
    Can my Above Application Run on Tiger.
    No.
    If not how do I interface ITune from Objective-C, on both Tiger and Leopard? IS there update which suppose to fix this?
    There will be no update for old products like Tiger. What there is is all you will ever get. For Tiger, you will have to dig into sending Apple Events to iTunes manually. Or it might be easier to define your Apple Scripts as string resources in your application an execute them via a system() call.

Maybe you are looking for