fatal error: unexpectedly found nil while unwrapping an Optional value using AVAudio

Question!

I've got two projects, using the same bit of code, but the following line:

player = AVAudioPlayer(contentsOfURL: NSURL(string: fileLocation), error: &error)

is returning this error in only one of the projects:

fatal error: unexpectedly found nil unwrapping an Optional value

The other project runs with no error.

I am trying to play a sound.

import UIKit
import AVFoundation


class ViewController: UIViewController {


    var player:AVAudioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        var fileLocation =  NSString(string: NSBundle.mainBundle().pathForResource("halloweenmp3", ofType: "mp3")!)

        var error: NSError? = nil

        player = AVAudioPlayer(contentsOfURL: NSURL(string: fileLocation), error: &error)

        player.play()


}

In both projects the same mp3 file has been added to the project but one project will play the sound while the other returns the error.

The project that is giving me the error does have other code in it, but the error only seems to relate to the line mentioned above so I don't see how another bit of code in the project could be causing it.

I've tried duplicating the error-prone project and get the same result. I've created new projects and use the same bit of code used above and had it work. I'm not sure if the project is corrupted somehow or another bit of code in the project is causing the error even though it's not being referred to in the debugger.

I can preview the mp3 file from the file navigator in xCode so it is working and is there.



Answers

You may do this:

  1. In your Project View, click your project name
  2. Select your target and Select "Build Phases" tab
  3. Drag your mp3 file into your "Copy Bundle Resources" section
By : Richter


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