Lastmboy
Lastmboy

Reputation: 1869

Trying to play system sound before speech recognition with SpeechKit

I'm trying to implement voice recognition in an iOS Swift app. When the user taps a "mic" button, I'm trying to play a system sound, then use SpeechKit to do voice recognition. The voice recognition works fine, and the sound plays fine, if I comment out the SpeechKit code. However, when I put them together, I get no sound. Also, I do not get the sound at the end, after the speech recognition completes.

Here is the code:

@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)
}

Either way, the voice recognition always works fine. If I comment that out, then the system sound plays fine.

e.g. the following will play the sound fine every time I tap the button:

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

I've tried different queues with no success. I'm thinking I need to move the SpeechKit code to a callback or closure of some type, but am not sure how to construct that.

Upvotes: 0

Views: 1525

Answers (1)

Anton Kondrashov
Anton Kondrashov

Reputation: 227

The solution to this problem is described here https://developer.apple.com/documentation/audiotoolbox/1405202-audioservicesplayalertsound

SpeechKit adds recording category to AVSession so the sounds are no longer played. What you want to do is this:

    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
    } 

Upvotes: 0

Related Questions