AVAudioPlayer不再使用Swift 2.0 / Xcode 7 beta

对于我的iPhone应用程序中的var testAudio声明,我在这里收到错误

“调用可以抛出,但错误不能从属性初始化程序中抛出”

 import UIKit import AVFoundation class ViewController: UIViewController { var testAudio = AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource("testAudio", ofType: "wav")!), fileTypeHint:nil) 

这发生在我转移到Xcode 7测试版时。

如何在Swift 2.0中使用此音频剪辑?

Swift 2有一个全新的error handling系统,你可以在这里阅读更多相关内容: Swift 2error handling 。

在您的情况下, AVAudioPlayer构造函数可能会抛出错误。 Swift不会让你使用在属性初始化器中抛出错误的方法,因为没有办法在那里处理它们。 相反,不要在视图控制器的init之前初始化属性。

 var testAudio:AVAudioPlayer; init() { do { try testAudio = AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource("testAudio", ofType: "wav")!), fileTypeHint:nil) } catch { //Handle the error } } 

这使您有机会处理创建音频播放器时可能出现的任何错误,并会阻止Xcode向您发出警告。

如果您知道不会返回错误,可以添加试试! 预先:

 testAudio = try! AVAudioPlayer(contentsOfURL: NSURL (fileURLWithPath: NSBundle.mainBundle().pathForResource 

适用于Swift 2.2

但是不要忘记将fileName.mp3添加到项目Build phases-> Copy Bundle Resources(右键单击项目根目录)

 var player = AVAudioPlayer() func music() { let url:NSURL = NSBundle.mainBundle().URLForResource("fileName", withExtension: "mp3")! do { player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil) } catch let error as NSError { print(error.description) } player.numberOfLoops = 1 player.prepareToPlay() player.play() }