0

我正在尝试在 iOS Swift 应用程序中实现语音识别。当用户点击“麦克风”按钮时,我正在尝试播放系统声音,然后使用 SpeechKit 进行语音识别。如果我注释掉 SpeechKit 代码,语音识别工作正常,并且声音播放正常。但是,当我将它们放在一起时,我没有声音。另外,在语音识别完成后,我最后没有听到声音。

这是代码:

@IBAction func listenButtonTapped(sender: UIBarButtonItem) {
    let systemSoundID: SystemSoundID = 1113
    AudioServicesPlaySystemSound (systemSoundID)

    let session = SKSession(URL: NSURL(string: "nmsps://{my Nuance key}@sslsandbox.nmdp.nuancemobility.net:443"), appToken: "{my Nuance token}")

    session.recognizeWithType(SKTransactionSpeechTypeDictation,
                          detection: .Long,
                          language: "eng-USA",
                          delegate: self)
}

func transaction(transaction: SKTransaction!, didReceiveRecognition recognition: SKRecognition!) {
    var speechString = recognition.text
    print(speechString!)

    let systemSoundID: SystemSoundID = 1114
    AudioServicesPlaySystemSound (systemSoundID)
}

无论哪种方式,语音识别都可以正常工作。如果我将其注释掉,则系统声音播放正常。

例如,每次我点击按钮时,以下内容都会很好地播放声音:

@IBAction func listenButtonTapped(sender: UIBarButtonItem) {
    let systemSoundID: SystemSoundID = 1113
    AudioServicesPlaySystemSound (systemSoundID)
}

我尝试了不同的队列,但没有成功。我在想我需要将 SpeechKit 代码移动到某种类型的回调或闭包中,但不知道如何构造它。

4

1 回答 1

0

此处描述了此问题的解决方案https://developer.apple.com/documentation/audiotoolbox/1405202-audioservicesplayalertsound

SpeechKit 将录音类别添加到 AVSession,因此不再播放声音。你想要做的是:

    let systemSoundID: SystemSoundID = 1113

    //Change from record mode to play mode
    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        try AVAudioSession.sharedInstance().setActive(true)
    } catch let error as NSError {
        print("Error \(error)")
    }
    AudioServicesPlaySystemSoundWithCompletion(systemSoundID) {
        //do the recognition
    } 
于 2017-07-21T09:51:17.623 回答