3

Hi I am trying to play a music file with a following code in swift 2. Basically I just dragged the audio file with a name f.mp3 to the asses folder and it my code breaks with the following message: unexpectedly found nil while unwrapping an Optional value. Where exactly I need to put my mp3 file so the IOS can find it. Thank you

var audioPlayer: AVAudioPlayer! = nil
func playMyFile() {

    let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3")
    let fileURL = NSURL(fileURLWithPath: path)

    do {
     try audioPlayer =  AVAudioPlayer(contentsOfURL: fileURL)
    } catch {
        print("error")
    }
    audioPlayer.prepareToPlay()
    audioPlayer.delegate = self
    audioPlayer.play()

}
jtbandes
  • 115,675
  • 35
  • 233
  • 266
M. Levin
  • 163
  • 1
  • 11
  • possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – jtbandes Sep 22 '15 at 06:36

1 Answers1

12

Your code is working fine with my project and here is my complete code:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer: AVAudioPlayer! = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        playMyFile()
    }

    func playMyFile() {

        let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3")
        let fileURL = NSURL(fileURLWithPath: path!)

        do {
            try audioPlayer =  AVAudioPlayer(contentsOfURL: fileURL)
        } catch {
            print("error")
        }
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }
}

Make sure your audio is added into Copy Bundle Resources like this:

enter image description here

If not added then add it this way:

enter image description here

Check THIS sample for more Info.

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165