无法播放斯威夫特的声音

时间:2016-05-10 23:03:19

标签: swift

我在播放连接到按钮/ IBAction的声音时遇到了一些麻烦。

当我在Xcode中为iOS做同样的事情时,它完美无缺。但是,当我为OS X执行此操作时,它不起作用。有什么想法吗?

import Cocoa
import AVFoundation

class ViewController: NSViewController, NSSpeechRecognizerDelegate {

var pingAudioPlayer : AVAudioPlayer?

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

func playPing(){
    let pingSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping", ofType: "mp3")!)
    pingAudioPlayer = AVAudioPlayer(contentsOfURL: pingSound, error: nil)
    pingAudioPlayer!.prepareToPlay()
    pingAudioPlayer!.currentTime = 0
    pingAudioPlayer!.play()
}


@IBAction func soundTest(sender: AnyObject) {
    playPing()
}
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"
    playPing()
}
override var representedObject: AnyObject? {
    didSet {
    // Update the view, if already loaded.
    }
}

}

1 个答案:

答案 0 :(得分:0)

主要问题是speechRecognizer方法,它不是正确的签名。

import AVFoundation

class ViewController: NSViewController, NSSpeechRecognizerDelegate {

    var pingAudioPlayer : AVAudioPlayer?

    var sr = NSSpeechRecognizer()

    @IBOutlet var output: NSTextView?

    func playPing(){
        let pingSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("ping", ofType: "mp3")!)
        pingAudioPlayer = try? AVAudioPlayer(contentsOfURL: pingSound)
        pingAudioPlayer?.prepareToPlay()
        pingAudioPlayer?.currentTime = 0
        pingAudioPlayer?.play()
    }

    @IBAction func soundTest(sender: AnyObject) {
        playPing()
    }

    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: String) {
        output?.string! += "\(command)\n"
        playPing()
    }

}