6

Due to injury I use dictation on MacOS:

enter image description here

As can be seen from the screenshot, I can toggle it using a keyboard shortcut.

I wish to toggle it from code (preferably ObjC).

I can manually inject the events:

// Assumes CTRL OPT CMD Space toggles dictation
void toggle_dictation()
{
    // NOTE: To return created event in tap-callback:
    //      cgEvent = [my_nsEvent CGEvent];
    //      CFRetain(cgEvent);

    //unsigned short keyCode_SPACE = 49;

    NSEvent* down_event = [NSEvent keyEventWithType: NSEventTypeKeyDown
                                           location: NSZeroPoint
                                      modifierFlags: NSEventModifierFlagControl | NSEventModifierFlagOption | NSEventModifierFlagCommand
                                          timestamp: 0.0
                                       windowNumber: 0
                                            context: nil
                                         characters: @" "
                        charactersIgnoringModifiers: @" "
                                          isARepeat: false
                                            keyCode: 0 /* keyCode_SPACE */ ];

    NSEvent* up_event = [NSEvent keyEventWithType: NSEventTypeKeyUp
                                         location: NSZeroPoint
                                    modifierFlags: 0
                                        timestamp: 0.0
                                     windowNumber: 0
                                          context: nil
                                       characters: @" "
                      charactersIgnoringModifiers: @" "
                                        isARepeat: false
                                          keyCode: 0 /* keyCode_SPACE */ ];

    CGEventPost(kCGHIDEventTap, [down_event CGEvent]);
    CGEventPost(kCGHIDEventTap, [up_event CGEvent]);
}

... but this is clumsy as it depends on my chosen shortcut.

Is there any way to do it with an API call?

P i
  • 29,020
  • 36
  • 159
  • 267

1 Answers1

2

Yes, there is:

NSSpeechRecognizer *recognizer = [[NSSpeechRecognizer alloc] init];
// start
[recognizer startListening];
// stop
[recognizer stopListening];

The full API is here:

https://developer.apple.com/documentation/appkit/nsspeechrecognizer?language=objc

jvarela
  • 3,744
  • 1
  • 22
  • 43