我正在跟踪Swift 1.0(偶然发生)的教程,它显示了如何播放声音。现在在Swift 2.0中,它将无法正常工作,请帮助。
import UIKit
import AVFoundation
class ViewController: UIViewController {
var ButtonAudioURL = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("cow", ofType: "wav")!)
var ButtonAudioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func playAudio(sender: AnyObject) {
ButtonAudioPlayer.play();
}
@IBAction func Stop(sender: AnyObject) {
}
}
最佳答案
使用do-catch语句通过运行代码块ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL)
来处理错误
//ButtonAudioPlayer = AVAudioPlayer(contentsOfURL: ButtonAudioURL, error: nil)
do {
ButtonAudioPlayer = try AVAudioPlayer(contentsOfURL: ButtonAudioURL)
} catch let error as NSError {
print(error.localizedDescription)
}