Swift 2种语言:AVAudio
Swift 2 language: AVAudio
大家好,现在 swift 2 已经成为我更改了一些与新编码语言不匹配的代码,唯一我不知道如何操作的是 AVAudioPlayer。这是我的:
var angryc:NSURL = NSBundle.mainBundle().URLForResource("MSoundEffect", withExtension: "mp3")!
angry = AVAudioPlayer(contentsOfURL: angryc, error: nil)
要我将 "error" 更改为 "FileTypeHint",当我更改时显示 "Call can throw, but is not marked with 'try'and the error is not handled"
任何帮助
我认为你应该使用 try 和 catch,因为 Swift 2.0 有一个新的错误处理。 AVAudioPlayer 可能会出错,您应该捕获这些错误。
var angryc:NSURL = NSBundle.mainBundle().URLForResource("MSoundEffect", withExtension: "mp3")!
do {
angry = try AVAudioPlayer(contentsOfURL: angryc, error: nil)
} catch _ {
fatalError ("Error loading \(angryc): \(error)")
}
另一种方法
当你确定AVAudioPlayer不会失败时,你也可以使用try!
如果失败,你的应用程序会崩溃!
您的代码如下所示
var angryc:NSURL = NSBundle.mainBundle().URLForResource("MSoundEffect", withExtension: "mp3")!
try! angry = AVAudioPlayer(contentsOfURL: angryc, error: nil)
来源:
https://developer.apple.com/videos/wwdc/2015/?id=106 在 39:30
大家好,现在 swift 2 已经成为我更改了一些与新编码语言不匹配的代码,唯一我不知道如何操作的是 AVAudioPlayer。这是我的:
var angryc:NSURL = NSBundle.mainBundle().URLForResource("MSoundEffect", withExtension: "mp3")!
angry = AVAudioPlayer(contentsOfURL: angryc, error: nil)
要我将 "error" 更改为 "FileTypeHint",当我更改时显示 "Call can throw, but is not marked with 'try'and the error is not handled" 任何帮助
我认为你应该使用 try 和 catch,因为 Swift 2.0 有一个新的错误处理。 AVAudioPlayer 可能会出错,您应该捕获这些错误。
var angryc:NSURL = NSBundle.mainBundle().URLForResource("MSoundEffect", withExtension: "mp3")!
do {
angry = try AVAudioPlayer(contentsOfURL: angryc, error: nil)
} catch _ {
fatalError ("Error loading \(angryc): \(error)")
}
另一种方法
当你确定AVAudioPlayer不会失败时,你也可以使用try!
如果失败,你的应用程序会崩溃!
您的代码如下所示
var angryc:NSURL = NSBundle.mainBundle().URLForResource("MSoundEffect", withExtension: "mp3")!
try! angry = AVAudioPlayer(contentsOfURL: angryc, error: nil)
来源: https://developer.apple.com/videos/wwdc/2015/?id=106 在 39:30