Search code examples
xcodeswift2ios9

Swift 2 language: AVAudio


Hi guys now that swift 2 has become I changed the few codes that don't match with the new coding language and the only thing that I don't know how to is the AVAudioPlayer. This is what I have:

var angryc:NSURL = NSBundle.mainBundle().URLForResource("MSoundEffect", withExtension: "mp3")!
angry = AVAudioPlayer(contentsOfURL: angryc, error: nil)

Want me to change the "error" to "FileTypeHint" and when i change it says "Call can throw, but is not marked with 'try'and the error is not handled" Any help


Solution

  • I think you should use try and catch, because Swift 2.0 has an new error handling. AVAudioPlayer can trow errors and you should catch these errors.

    var angryc:NSURL = NSBundle.mainBundle().URLForResource("MSoundEffect", withExtension: "mp3")!
    do {
        angry = try AVAudioPlayer(contentsOfURL: angryc, error: nil)
    } catch _ {
        fatalError ("Error loading \(angryc): \(error)")
    }
    

    another method

    When you are sure that the AVAudioPlayer won't fail, you can also use try! If it fails, your app will crash!

    Your code would look like this

    var angryc:NSURL = NSBundle.mainBundle().URLForResource("MSoundEffect", withExtension: "mp3")!
    try! angry = AVAudioPlayer(contentsOfURL: angryc, error: nil)
    

    Source: https://developer.apple.com/videos/wwdc/2015/?id=106 at 39:30

    more info here about try catch

    and here about AVAudioPlayer