How to initialize AVAudioPlayer using Swift

Question!

I'm creating a game using Swift and SpriteKit in Xcode 6.1 and I can't get AVAudioPlayer to initialize. I have an SKScene for my menu, and I want to run music in my "Sounds" folder called "menu.mp3." However, it crashes every time I run my game. My code is below:

let filePath:NSURL = NSURL(fileURLWithPath: "menu.mp3")!
var er:NSError?
let audioPlayer:AVAudioPlayer = AVAudioPlayer(contentsOfURL: filePath, error: &er)

if (er != nil) {
} else {
     audioPlayer.play()
}

I put this in my initializer right after my super.init call. The error I get follows:

fatal error: unexpectedly found nil while unwrapping an Optional value

I've tried a lot of fixes, but I can't figure out what's going wrong. I've added the AVFoundation framework and imported it to this scene, but it continues to crash. Is there something wrong with my filePath that makes my audioPlayer not initialize or something? I've tried switching to other ways and making different parts optional, but I can't get it to work. Thanks!

By : nphirning


Answers
let documentsUrl =  NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as NSURL
func preparePlayer(name:String){
    var error:NSError?

    let fileUrl = documentsUrl.URLByAppendingPathComponent(name)
//    or 
//    let fileUrl = NSBundle.mainBundle().bundleURL.URLByAppendingPathComponent(name)

    let audioPlayer = AVAudioPlayer(contentsOfURL: fileUrl, error: &error)
    if error == nil {
        audioPlayer.play()
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    preparePlayer("menu.mp3")
}
By : Leo Dabus


This video can help you solving your question :)
By: admin