2016-05-10 178 views
0

播放連接到按鈕/ IBAction的聲音時遇到了一些問題。無法播放聲音Swift

當我在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. 
    } 
} 

}

回答

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

}