Trigger Media events in Applescript?

Hello,
I've been searching a lot on this and i cant for the life of me find how to trigger media events in Applescript.
I have found that i can tell specific applications to playpause like itunes for example, this is not what i want.
What im trying to do is make an applescript that behaves like the play/pause button that you can find on any Apple Keyboard when executed.
I imagined that this would be as simple as to tell System Events to trigger a media event, regretfully this does not work.
If anyone could shed some light on this i would greatly appreciate it!
Regards,
Jonathan

Hello
Some time ago I've written a rubycocoa code to post media key events. Here's an AppleScript wrapper for it.
Code is tested under 10.6.8. This won't work under 10.5.8. Don't know about later versions.
Regards,
H
PS. If you're just trying to keep iTunes from launching when PLAY_PAUSE key is pressed, this script is not what you need. The rcd daemon is the culprit to launch iTunes by that specific key and so you'd need to "fix" it by modifying its executable. There's a tried and true method to do it, which I myself has employed.
--post_media_key_events("MUTE", 1, 0, {})
--post_media_key_events("VOLUME_UP", 12, 0.01, {option down, shift down})
--post_media_key_events("VOLUME_DOWN", 12, 0.01, {option down, shift down})
post_media_key_events("PLAY_PAUSE", 1, 0, {})
on post_media_key_events(subtype, k, d, mods)
        string subytpe : event subtype name, one of the following -
                VOLUME_UP
                VOLUME_DOWN
                BRIGHTNESS_UP
                BRIGHTNESS_DOWN
                MUTE
                PLAY_PAUSE
                FORWARD
                REWIND
                ILLUMINATION_UP
                ILLUMINATION_DOWN
        integer k : number of key repeat
        number d : delay inserted after each key release [sec]
        list mods : any combination of the following enumerations
                shift down
                option down
                command down
                control down
                caps lock down
                * constants other than listed above are ignored
    set args to ""
    repeat with m in mods
        set m to m's contents
        if m = shift down then set args to args & space & "shift"
        if m = option down then set args to args & space & "option"
        if m = command down then set args to args & space & "command"
        if m = caps lock down then set args to args & space & "capslock"
    end repeat
    set args to subtype & space & k & space & d & space & args
    considering numeric strings
        if (system info)'s system version < "10.9" then
            set ruby to "/usr/bin/ruby"
        else
            set ruby to "/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby"
        end if
    end considering
    do shell script ruby & " <<'EOF' - " & args & "
require 'osx/cocoa'
include OSX
class AppDelegate < NSObject
    # event subtypes
    # cf. /System/Library/Frameworks/IOKit.framework/Versions/A/Headers/hidsystem/ev_keymap.h
    VOLUME_UP             = 0
    VOLUME_DOWN             = 1
    BRIGHTNESS_UP         = 2
    BRIGHTNESS_DOWN         = 3
    MUTE                 = 7
    PLAY_PAUSE             = 16
    FORWARD                = 19
    REWIND                 = 20
    ILLUMINATION_UP         = 21
    ILLUMINATION_DOWN    = 22
    # keyboard event
    # cf. /System/Library/Frameworks/IOKit.framework/Versions/A/Headers/hidsystem/IOLLEvent.h
    KEYDOWN                = 10
    KEYUP                = 11
    def initWithArguments(args)
        @subtype, @count, @delay, *@mods = args
        @count = @count.to_i
        @delay = @delay.to_f
        @mods = @mods.join(' ')
        self
    end
    def applicationDidFinishLaunching(notif)
        begin
            @win = NSWindow.alloc.objc_send(
                :initWithContentRect, NSMakeRect(0, 0, 600, 600),
                :styleMask, NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask,
                :backing, NSBackingStoreBuffered,
                :defer, false)
            @win.setLevel(NSStatusWindowLevel)
            @win.center
            if NSApp.respondsToSelector?('setActivationPolicy')                    # 10.6 or later only
                NSApp.setActivationPolicy(NSApplicationActivationPolicyRegular)
            end
            NSApp.activateIgnoringOtherApps(true)
            ev1 = createMediaKeyEvent(@win, @subtype, 'keydown', @mods)
            ev2 = createMediaKeyEvent(@win, @subtype, 'keyup', @mods)
            @count.times do
                postMediaKeyEvent(ev1)
                postMediaKeyEvent(ev2, @delay)
            end
        ensure
            NSApp.terminate(self)
        end
    end
    def applicationShouldTerminateAfterLastWindowClosed(app)
        true
    end
    def applicationShouldTerminate(sender)
        NSTerminateNow
    end
    def createMediaKeyEvent(win, subtype, keystate, modifiers = '')
        #    NSWindow win : target window device which receives the event
        #    uint16 subtype : event subtype for event type = NSSystemDefined
        #    string keystate : one of ['keydown', 'repeat', 'keyup']
        #    string modifiers : modifier key names (shift control option command capslock) separated by white space
        mtable = {
            'capslock'    => KCGEventFlagMaskAlphaShift,
            'shift'        => KCGEventFlagMaskShift,
            'control'    => KCGEventFlagMaskControl,
            'option'    => KCGEventFlagMaskAlternate,
            'command'    => KCGEventFlagMaskCommand,
        mflag = modifiers.split.inject(0) { |mflag, x| (m = mtable[x]) ? mflag | m : mflag }
        mflag |= KCGEventFlagMaskNonCoalesced
        kstate =
            case keystate
                when 'keydown'    then KEYDOWN << 8
                when 'keyup'    then KEYUP << 8
                when 'repeat'    then KEYDOWN << 8 | 1
                else 0
            end
        raise ArgumentError, %[invalid keystate : #{keystate}] if kstate == 0
        raise ArgumentError, %[unsupported media key event subtype : #{subtype}] unless
                VOLUME_UP,
                VOLUME_DOWN,
                BRIGHTNESS_UP,
                BRIGHTNESS_DOWN,
                MUTE,
                PLAY_PAUSE,
                FORWARD,
                REWIND,
                ILLUMINATION_UP,
                ILLUMINATION_DOWN,
            ].include?(subtype)
        data1 = subtype << 16 | kstate
        data2 = 0xffffffff
        event = NSEvent.objc_send(
            :otherEventWithType, NSSystemDefined,
            :location, NSMakePoint(0.0, 0.0),
            :modifierFlags, mflag,
            :timestamp, 0,
            :windowNumber, win.windowNumber,
            :context, win.graphicsContext,
            :subtype, 8,
            :data1, data1,
            :data2, data2)
        raise RuntimeError, %[failed to create event] unless event
        return event
    end
    def postMediaKeyEvent(event, delay = 0.0)
        CGEventPost(KCGHIDEventTap, event.CGEvent)
        sleep delay
    end
end
def main
    raise ArgumentError, %[Usage: #{File.basename($0)} subtype [count [delay [modifiers]]]] unless ARGV.length > 0
    begin
        s, k, d, *mods = ARGV
        subtype = AppDelegate.const_get(s.to_sym)
        k = k ? k.to_i : 1
        d = d ? d.to_f : 0.0
    rescue => ex
        $stderr.puts %[#{ex.class} : #{ex.message}]
        exit 1
    end
    args = [subtype, k, d] + mods
    app = NSApplication.sharedApplication
    delegate = AppDelegate.alloc.initWithArguments(args)
    app.setDelegate(delegate)
    app.run
end
if __FILE__ == $0
    main
end
EOF"
end post_media_key_events

Similar Messages

  • BRF+ Trigger via Event, change on field value, etc

    Hi,
    I'm implenting BRF+ for SPM Claims & Returns Process.
    It took me a while to understand how I can set up an application, Function from type event, Rulesets, rules, etc but at the end it seems that it is a tremendous improvement compared to BRF!
    So far I have triggered the BRF+ via the CRMV_EVENT_CUST table calling a function module that triggers the BRF+ Function and receives an CRM Log message but this solution is not sufficient for all locations I want to call the BRF+.
    At first I want to call the BRF+ for the Entryvalidation: Entering a Claim with a item net value below a threashold should not be saveable.
    The second call should be to decide if the Claim will be automatically approved or set to manual investigation: This is a check that will lead to a item status change.
    The third and last check will be fullfilled by saving the Claim document: a whole set of business rules have to run and set maybe an incompleteness or process some error messages.
    I neither any information in SAP Documentation, nor on any ressource on the net any information about customing the BRF+ Solution.
    Is there any customizing in the system, as it is for BRF, that allows me to trigger the BRF+ for Business Transaction Category, Business Transaction or ItemCategories?
    Furthermore, is there an option to call BRF+ via customizing that "listens" to a field change as Reason Code ( CODEGRUPPE, KATALOGART,CODE in the Subjectprofile?)
    Can I define Events that trigger the BRF+ as in the BRF customizing?
    When I search the IMG for BRFPLUS, I find a couple of entries, but doubleclicking on this search results doesn't jump to the customizing step.
    It would be very helpfull to get some input in these topics.
    Kind regards,
    Sven

    Hi Tiwari,
    yes, the screenshot was from CRM-Financial, but available in CRM Transaction Processing:
    And I agree to your statement that there is no such customizing, because I neither found this Customizing, except:
    Using the search in the customizing IMG, you will find 3 customizing entries with BRF+ or BRFPLUS, but clicking on them you will land in Nirvana, and not in the proper customizing tree.
    But still the overall trigger for my message here is, that the BRF could be triggered via Customizing that doesn't seem to exist for BRF+ and that's strange!
    I hope someone knows how the replacement of BRF with BRF+ is intended from this customizing point of view. I have to trigger a lot of different functions and using the old BRF I could trigger this Events using this customizing setup.
    Thanks,
    Sven

  • Automatically trigger the event to load data from Planning cube to Standard Cube

    Hello,
    We have a below set up in our system..
    1. A Planning BEx query using which user makes certain entries and writes back data to the planning cube.
    2. An actual reporting cube which gets data from the planning cube above.
    Now, what we want to do is to automate the data load from Planning cube to Reporting cube.
    This involves 2 things..
    1. Change the setting " Change real time load behaviour " of the planing cube to Planning.
    2. Trigger the DTP which loads data from Planning cube to reporting cube.
    We want to automate the above two steps...
    I have tried few things to achieve the same..
    1. Created an event in SM64,
    2. In the Planning cube "Manage" Screen,  clicked on "Subsequent Processing" and provided the event details. ( Not sure if its the correct place to provide the event detail ).
    3. Wrote a ABAP program which changes the setting of the planning cube (  " Change real time load behaviour " to Loading )
    4. Created a process chain, where we have used the event as a start variant, used the ABAP program as a next step, DTP run as the last step..
    This i hoped, would trigger the event as soon as a new request comes and sits in planning cube, which in turn would trigger the process chain which would load the data from Planning cube to reporting cube..
    This is not working. I dont think the event is triggering, and even if does i am not sure whether it will start the process chain automatically. Any ideas please ?

    hi,
    try to do the transformation directly in the input cube by using CR of type exit, more details :
    http://help.sap.com/saphelp_nw70ehp2/helpdata/en/43/1c3d0f31b70701e10000000a422035/content.htm
    hope it helps.

  • How can I trigger an event from an ABAP Program

    Hi everyone,
    I have a requirement, where I have to create an ABAP program, that has to execute (trigger) an event which belongs to a Process Chain. when I run the program, the Process Chain has to run.
    So, how can I do it?
    Thanks for your help, Federico

    HI ,
    The program can call function module BP_EVENT_RAISE to raise the event. you can create vent in sm64 and sm62 .There you give the parameter of the event same as what you will define in the event of start variant of your process chian ..
    Regards,
    shikha

  • Trigger an event in the parent view, when popping a child view (Mobile)

    So from one view I'm pushing another view with some data:
    <s:Button label="Edit System" click="navigator.pushView(EditSystem, systems.selectedItem)"/>
    The problem I have is that in this other view I'm updating a view things in my sqlite database, so when I pop the 'EditSystem' view and return to the original, I want to run a function to requery the the sql so I can update a view things in the original view. But from what I can fugure Eventlisteners dont work across views? How do I trigger an event in the original view when I return from a child view via pop? 

    You should find this post useful: http://flexponential.com/2010/12/05/saving-scroll-position-between-views-in-a-mobile-flex- application/
    It demonstrates one way of saving and restoring data when pushing and popping a view.

  • Is it able to refresh the table view automaticlly after trigger an event?

    Hi expert,
    I have one table view and a "Delete" button, each time when the user click the del button, it will delete the row which is selected via a RFC module in the backend, afterwards, I want this table view to be refreshed and read the real data from backend via another function module, is it possible? how could I do it?
    Thanks and best regards

    Let me do some summarize if my understanding is correct
    1. Use a timer as "start" point of a table view, set the "interval" to be 0.05 minute
    2. use the condition in the timer with a formula (BOOL(STORE@RETURN_CODE==0)).
    3. If I trigger one event in the "table view", for example, a "Delete" event and it will return the result RETURN_CODE = 0 to datastore
    4. Afterwards, if the time interval of the timer has been reached, 1st it will evaluate the value of the datastore and decide whether to refresh the table view.
    Am I right?
    Just as you mentioned before, it is not a perfect solution, as we may still wait for the timer to be triggered after a few seconds.
    Thanks for your answer.

  • Using the keydown option in order to trigger an event

    Hi all,
    This is my first question on this forum, and that is probably because i just started learning labview.
    I came across with an error, i could most likely solve in another programming language using C, but not in labview.
    I was wondering if someone could give me a hand with the following:
    I attached the program, which is probably a bit bad-written. Basicly, what im trying with the part on the left, is read all values from a controller on a GPIB bus.
    This part works like a charm, because i get all the values i want without any problem. After that, in the last step of this program, you have a while loop, with in there an event structure. The reason i took a while for that is because i dont want the program to start over at step 1. The event structure was first used with clicks of the mouse on the buttons, and a changed value with the numeric controls. Because a changed value did not work, cause the loop was constantly reading the values coming from the initial phases, i wanted to change the way the events were handled by a keydown of 'Enter'. I think, when you change a value in a numeric control and press enter, this could be perfectly used to trigger the events, instead of the value changes (because everytime the program reads the values in the sides, i think its considered like a value change). The fact is i dont really have an idea how to use the keydown as an event handler, any info on this would be greatly appreciated.
    I'm sorry if my english isn't the best, it's only my 3th language. Hope you understood and i can get some help for this issue
    Thanks in advance
    Thomas De Landtsheer
    Student
    Solved!
    Go to Solution.
    Attachments:
    Labview detection of keystroke.vi ‏197 KB

    The problem is a few
    blocks we havent really seen yet. All these numerics and stuff outside
    the while loop, what are they exactly, or are they just a different way
    of viewing them? The stuff with the digital at INI phase, The block
    in the lower right corner of the INI phase.
    The digital block in the
    dispatcher phase we didn't really understand. 
    I am not sure what you mean here can you circle it and send me a picture so that I can explain.
    Tim
    Johnson Controls
    Holland Michigan

  • How to trigger left_click_run event on ALV GRID

    Hiiiiiiii........
    Can any of u please tell me how to trigger left_click_run event on ALV GRID.
         There is an event LEFT_CLICK_RUN and  its a public accessed event. But the problem is , the corresponding  attribute of this event  "EVENT_LEFT_CLICK_RUN" which is needed to registered that event (We need to register our events through a method set_register_events  using table of type cntl_simple_events...) is protect accessed. So I am unable to use that attribute...Could u please tell  me is there any alternative way to register that event.......ANY POSSIBLE WAY?
    Thanks in advance,
    Rams

    I think you should use event selection_changed. Note that you shouldn't allow multiple selection for the tree at the same time, i.e. use: create object g_tree exporting \[...\] node_selection_mode = cl_gui_column_tree=&gt;node_sel_mode_single.
    For more information, see this thread: Urgently required :  cl_gui_alv_tree single_click event...

  • How to trigger own events?

    How can you create your own events to be triggered?
    For instance, I have an InputStream that I've got through a Socket that's listening for incoming data. I want to signal/trigger an event when data comes in so that the gui (in another class) can take appropriate actions. How can you do this?

    The basic idea is this:
    public interface SockeListener
        void dataEvent(/* pass a parameter if needed.  Often an event interface is added */);
    public class MySocket
         private final List listeners = new ArrayList();
         public void addListener(SocketListener listener)
              listeners.add(listener);
         public void removeListener(SocketListener listener)
              listeners.remove(listener);
         private void triggerEvent()
               for (Iterator i = listeners.iterator(); i.hasNext();)
                    ((SocketListener) i).dataEvent();
    }Check out the PropertyChangeSupport class also.

  • How can I trigger an event handler, based on a history dropdown select (onclick)

    Hi
    Firefox remembers user names and email addresses previously entered in text input fields. I wish to trigger an event-handler when an item has been selected.
    Best regards, Jens Larsen

    I figured out part of this. I had the event listener
    listening to the spry select id, I set an id on the select and the
    input lines and it's working correctly. Now I just have to push the
    changes to the database.

  • Writing a program using an output from a NAND gate to trigger an event.

    I'm using a PCI 6024E with a CB 68 board and Visual Basic 6.
    I would like to trigger an event when the output signal from a NAND gate is high. Do I have to use a DO loop to keep checking for this trigger?

    Hello;
    If you want to use the DAQ board you have there, you will need to keep polling the digital line to recognize the state change.
    If you need something more accurate, you can use one of the digital boards, such as the PCI-DIO-32HS, and do change detection on the digital lines.
    Hope this helps.
    Filipe A.
    Applications Engineer
    National Instruments

  • How do i get a boolean indicator to trigger a event structure

    I have two parallel loops running, and i need to use a boolean value, one that comes out from an OR gate, to trigger an event in the parallel, event structure loop.  I've attached a simplified version of the loop.  Is there a way to get this done?  I've tried using local variables, value(signaling), etc. and they haven't worked
    Solved!
    Go to Solution.
    Attachments:
    Parallel Loop Trigger.vi ‏10 KB

    Here is a revised version of your VI. I modified the mechanical actino of the stop button so it kept it's value until it was read. In addition, I added a delay to your upper loop. Without a delay it was running too fast to actually see the button press. I modifed the event in the the event structure to trigger on a value change of Boolean.
    You don't really need the outer loop since it will only run a single time in all instances. On the first execution of that loop it will be sitting in the turn inner loops. Once you exit the two inner loops your outer loop will always exit. Therefore, it serves no purpose.
    Your OR in the upper loop is completely uses. It serves no purpose since the result will always be equal to the value of the Stop button.
    There are better ways of triggering events. a preferred method would be to use a user event and simply generate the event at the appropriate time. This has the advantage of not requiring additional controls/indicators simply to cause an event to occur.
    Mark Yedinak
    "Does anyone know where the love of God goes when the waves turn the minutes to hours?"
    Wreck of the Edmund Fitzgerald - Gordon Lightfoot
    Attachments:
    Parallel Loop Trigger.vi ‏12 KB

  • How to trigger an event in the program

    Hi,
    I have a program. The purpose of the program is to retrieve the data matching the selection criteria and downlod the same to a file.
    In the selection screen, I have a parameter called 'EVENT'. Here, user enters some event name. Generally, they enter the 'Background job processing events'.
    So, my requirement is... once the files are successfully downloaded, the program should trigger the 'EVENT' specified in the selection screen at run time.
    Can someone help me in this regard. How to trigger an EVENT in the program. Is there any Function Module or Method available in SAP which triggers the EVENT at runtime.
    And is there any table available in SAP which stores all the events available in SAP. Because, whenever the user enters an EVENT in the selection screen, we should check whether the event is valid or not. So, if there is any table available which has all the events then, it will be easy I guess. or is there any other way to validate the EVENT name.
    Please help me. Thanks in advance,
    Best Regards,
    Paddu.

    Hello Paddu,
    have a look at tables
    - btcsev, btcsed (system events)
    - btcuev, btcued (user events)
    and use function BP_EVENT_RAISE.
    kind regards
    Walter Habich

  • Trigger DATA_CHANGED event from triggered DATA_CHANGED event in second ALV

    Hello,
    I do have 2 ALVs (class CL_GUI_ALV_GRID) in a Splitter-Control.
    Both ALVs do have registered the event DATA_CHANGED in seperate handler methods.
    If there is a change in first ALV(line insertion with values), there will be inserted a new line with values in the second ALV.  After handling the event at first ALV, I call CHECK_CHANGED_DATA of the second ALV and REFRESH_TABLE_DISPLAY of the second ALV. I would expect that the call of CHECK_CHANGED_DATA would trigger the event DATA_CHANGED, but it does not trigger the event DATA_CHANGED of the second ALV.
    The problem is maybe that the input at the data is not made by the user(UI).
    What could I do to trigger this event and check the new data at second ALV?
    Yours Joerg

    Hello ,
    yeah thats correct , but in your case what you can do is
    g_grid1(first alv) >CHECK_CHANGED_DATA( Importing E_VALID =  l_Valid )>in the implementation method of this ..update global variable g_second = 'X' in order to refresh ALV2.
    g_grid1(first alv) -->Refresh_table_display( ).
    if g_second = 'X'.
    g_grid2-->SET_TABLE_FOR_FIRST_DISPLAY. so it will refresh the second alv contents.
    endif.
    regards
    Prabhu

  • How to trigger a event when WBS gets changed in Cj02

    Hello,
    I have a requirement where I need to send create an idoc and send the idoc to external system when WBS is created or changed.  Currently, I have the following setup:
       - I have created a YBUS2054 as a subtype of BUS2054 using SWO1
       - YBUS2054 has been delegated to BUS2054
       - created an CHANGED event in the YBUS2054. This event is implemented and then released
       - created a type linkage (object type=YBUS2054, event=CHANGED, receiver type null, and receiver function module = zz_create_wbs_idoc) using SWETYPV. This function is supposed to create an idoc when CHANGED event occurs. I just don't know how to trigger the event to occur.
       - all the port, define idoc type, logical system, and etc are setup
       - when I try to create an entry in "Event for Chagne Document" using SWEC with change doc object=PROJ, business object type = YBUS2054, with on change, I get "Key for change doc object PROJ and business object type YBUS2054 are incompatible".
    I tried various configurations, and I was not successfully in creating an event on CHANGED
    can you please advise what I am missing in getting the changed event to trigger?
    Thank you in advance,
    Shawn

    Hi,
    If the change doc doesnt exist, check if you can create an event using BSVW.
    Also use the event log to see if there are other sap standard events happening.
    I checked the package belonging to CJ02 to see if there is something useable, but didn't find anything: CN_PSP_OPR
    If there are no sap standard ways to get an event, you'll have to find a badi/enhancement spot and include some coding to start the event using fm SAP_WAPI_CREATE_EVENT.
    Kind regards, Rob Dielemans

Maybe you are looking for