Programmatically toggle dictation on MacOS
Asked Answered
T

1

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?

Tacita answered 5/7, 2019 at 3:55 Comment(3)
This may help... discussions.apple.com/thread/4533177Permenter
https://mcmap.net/q/1916239/-using-mac-s-dictation-inside-pythonSheff
If it helps, you can also use Siri to turn dictation on and offSheff
P
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

Prophetic answered 18/7, 2019 at 17:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.