【问题标题】:How to Start Dictation programmatically? [closed]如何以编程方式开始听写? [关闭]
【发布时间】:2015-04-15 21:24:26
【问题描述】:

我想将麦克风图标添加到我的应用程序中并开始听写。有没有办法在 Swift 中以编程方式开始听写?除了解析编辑菜单并获得正确的菜单项?

我做了这个解决方法,它可以工作,但是......:

@IBAction func startDictation(sender: AnyObject) {
    if wordInputField.acceptsFirstResponder {
        self.makeFirstResponder(wordInputField)
    }

    if let menuItem = dictationMenuItem("startDictation:") {
        NSTimer.scheduledTimerWithTimeInterval(0, target: menuItem.target!, selector: menuItem.action, userInfo: nil, repeats: false)
    }
}

func dictationMenuItem(selectorName : String) -> NSMenuItem? {
    var edit = NSApplication.sharedApplication().mainMenu?.itemWithTitle("Edit")
    if let count = edit?.submenu?.numberOfItems {
        let lastItem = edit?.submenu?.itemAtIndex(count - 2)
        if lastItem?.action == NSSelectorFromString(selectorName) {
            return edit?.submenu?.itemAtIndex(count - 2)
        }
    }
    return nil
}

【问题讨论】:

  • “它可以工作,但是...” ...但是什么?如果它有效,你在问什么?

标签: macos swift dictation


【解决方案1】:

更新

我认为您需要启动 SpeechRecognitionServer...

osascript -e 'tell application "SpeechRecognitionServer"
   set theResponse to listen for {"yes", "no"} with prompt "Hello. Do you like me?"
   if theResponse is "yes" then
       say "I like you, too."
   else
       say "Am I bovvered?"
   end if
end tell'

原答案

你可以从 Applescript 开始听写,也可以从 Swift 开始 Applescript,所以有一个迂回的方法可以让你继续前进,直到比我更聪明的人解决“正确”方式:-)

#!/usr/bin/env xcrun swift

import Foundation

let task = NSTask()
task.launchPath = "/usr/bin/osascript"
task.arguments = ["-e","tell app \"System Events\" to key code {63,63}"]

task.launch()

相当于在键盘上按了两次fn键——keycode 63。

【讨论】:

  • 但如果用户更改了此 fnfn 热键,它将不起作用
  • 这是真的....讨厌的用户!总是惹麻烦:-)
  • 谢谢马克。但这并不是我所需要的。我可以创建 NSSpeechRecognizer 并检测命令。但是我正在开发一个翻译应用程序,所以我想使用听写来翻译未知单词。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
  • 1970-01-01
  • 2011-03-07
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
相关资源
最近更新 更多