在MacOS上以编程方式切换听写

时间:2019-07-05 03:55:51

标签: macos speech-recognition speech-to-text dictation

由于受伤,我在MacOS上使用了命令:

enter image description here

从屏幕截图中可以看出,我可以使用键盘快捷键对其进行切换。

我希望从代码(最好是ObjC)中进行切换。

我可以手动注入事件:

// 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]);
}

...但是这很笨拙,这取决于我选择的快捷方式。

有什么方法可以通过API调用吗?

1 个答案:

答案 0 :(得分:2)

是的,有:

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

完整的API在这里:

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