gpt4 book ai didi

swift - 使用 NSSpeechRecognizer Swift 触发声音 play()

转载 作者:行者123 更新时间:2023-11-30 13:26:53 25 4
gpt4 key购买 nike

我试图在说出一个词后触发声音。当我说出该单词时,语音识别器会识别该单词,并且我已将其设置为每次我说出该命令时它都会输出一个字符串。我想做的是在我说出特定单词后触发声音。这就是我到目前为止所拥有的。

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.
}
}

更新:

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.
}
}

}

不知道为什么音频播放器在识别单词后不播放声音。有什么想法吗?

最佳答案

您没有告诉音频播放器要播放哪种声音。试试这个:

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

关于swift - 使用 NSSpeechRecognizer Swift 触发声音 play(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com