Pjc1992 Pjc1992 - 7 months ago 89
Swift Question

Trigger sound play() with NSSpeechRecognizer Swift

I'm trying to trigger a sound after I say a word. The speech recognizer recognizes the word when I say it and I've set it up so it puts out a string each time I say the command. What I'd like to do is trigger a sound after I say that specific word. This is what I have so far.

import Cocoa
import AVFoundation

class ViewController: NSViewController, NSSpeechRecognizerDelegate {

var ping = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping", ofType: "mp3")!)
var pingAudioPlayer = AVAudioPlayer()

var sr = NSSpeechRecognizer()
@IBOutlet var output: NSTextView?


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
pingAudioPlayer = AVAudioPlayer(contentsOfURL: ping, error: nil)

sr.delegate = self
sr.commands = ["Ping", "Ping Mac"]
sr.startListening()

}

func speechRecognizer(sender: NSSpeechRecognizer, didRecognizeCommand command: AnyObject?) {
output!.string! += "\(command)\n"
pingAudioPlayer.play()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}


UPDATE:

import Cocoa
import AVFoundation

class ViewController: NSViewController, NSSpeechRecognizerDelegate {

var ping = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping", ofType: "mp3")!)
let pingAudioPlayer = AVAudioPlayer()

var sr = NSSpeechRecognizer()
@IBOutlet var output: NSTextView?


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
sr.delegate = self
sr.commands = ["Ping", "Ping Mac"]
sr.startListening()


}

func speechRecognizer(sender: NSSpeechRecognizer, didRecognizeCommand command: AnyObject?) {
output!.string! += "\(command)\n"
var pingAudioPlayer = AVAudioPlayer(contentsOfURL: ping, error: nil)
pingAudioPlayer.prepareToPlay()
pingAudioPlayer.play()
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}


}

Not sure why the audio player is not playing the sound once the word is recognized. Any ideas?

Answer

You aren't telling the audio player which sound to play. Try this:

func speechRecognizer(sender: NSSpeechRecognizer, didRecognizeCommand command: AnyObject?) {

do{
    let pingAudioPlayer = try AVAudioPlayer(contentsOfURL:ping)
    pingAudioPlayer.prepareToPlay()
    pingAudioPlayer.play()
}catch {
    print("Error getting the audio file")
 }
}