我正在尝试使用Apple的Speech框架在macOS 10.15.1上进行语音识别。在macOS 10.15之前,语音识别仅在iOS上可用,但根据文档和本讲座,现在也应该在macOS上可用。
但是,我所有使用它的尝试都导致SFSpeechRecognizer
的isAvailable
属性设置为false。根据演讲内容和文档,我启用了Siri,并确保我的应用"Privacy - Speech Recognition Usage Description"
在Info.plist中将键设置为字符串值。
我还尝试过启用代码签名(此问题表明可能是必要的),在“系统”偏好设置中的“键盘”>“听写”下启用“听写”。
这是一些示例代码,尽管具体细节可能并不重要。我已经使用Storyboard而不是SwiftUI进行了尝试,将回调的SFSpeechRecognizer
内部和外部实例化,requestAuthorization
未指定语言环境,等等。似乎没有任何效果:
import SwiftUI
import Speech
struct ContentView: View {
func tryAuth() {
SFSpeechRecognizer.requestAuthorization { authStatus in
switch authStatus {
case .authorized:
print("authorized")
case .denied:
print("denied")
case .restricted:
print("restricted")
case .notDetermined:
print("notDetermined")
@unknown default:
print("unanticipated auth status encountered")
}
}
}
func speechTest() {
guard let recognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US")) else {
// Not supported for device's locale
print("couldnt get recognizer")
return
}
if !recognizer.isAvailable {
print("not available")
return
}
print("Success")
}
var body: some View {
VStack {
Button("Try auth") {
self.tryAuth()
}
Button("Test") {
self.speechTest()
}
}
}
}
尤其奇怪的是,如果我运行该应用程序,然后单击“ Try auth”按钮,authStatus
则回调始终为.authorized
。但是,我从来没有出现过一个对话框,要求我对应用程序进行授权,并且该应用程序不会显示在“系统偏好设置”>“安全性和隐私”>“隐私”>“语音识别”下的授权应用程序列表中。
尽管如此,单击“测试”按钮之后仍会打印not available
。
我对macOS隐私/权限系统的理解似乎有些空缺,但我不确定如何进一步调试。我还认为应该可以使此工作正常进行,因为我在StackOverflow上看到了其他问题,暗示人们已经这样做了,例如here,here。
编辑:在评论的建议下,我尝试isAvailable
通过用代码替换我对它的检查以实际尝试转录文件的方式来忽略该错误的事实,例如:
let request = SFSpeechURLRecognitionRequest(url: URL(fileURLWithPath: "/Users/james/Downloads/test.wav"))
recognizer.recognitionTask(with: request) { (result, error) in
guard let result = result else {
print("There was an error transcribing that file")
print("print \(error!.localizedDescription)")
return
}
if result.isFinal {
print(result.bestTranscription.formattedString)
}
}
然后失败,打印:The operation couldn’t be completed. (kAFAssistantErrorDomain error 1700.)
。因此,似乎确实有必要进行检查isAvailable
,而我的问题仍然是:如何使其成为现实true
?
有类似问题SFSpeechRecognizer ......或许你可以设置的委托SFSpeechRecognizer
请求授权之前,如图所示这里。
例如:
class ViewController: NSViewController {
var speechRecognizer: SFSpeechRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))
speechRecognizer.delegate = self
}
override func viewWillAppear() {
SFSpeechRecognizer.requestAuthorization { authStatus in
...
}
if !speechRecognizer.isAvailable {
print("Not available!")
}
let url = Bundle.main.url(forResource: "sample", withExtension: "mp3")!
let request = SFSpeechURLRecognitionRequest(url: url)
// will now ask for authorisation
speechRecognizer.recognitionTask(with: request) { (result, error) in
...
}
}
}
extension ViewController: SFSpeechRecognizerDelegate {
}
然后将正确显示授权对话框。
此外,似乎只有在呼叫时recognitionTask
,才会要求用户给予许可。相反,requestAuthorization
单独打电话不会有任何效果。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句