-1

Working on a project, I decided to add some music to play when a certain action is triggered. Here's what I've got:

var player : AVAudioPlayer?

several lines later...

func playSound(){
    let alertSound = URL(fileURLWithPath: Bundle.main.path(forResource: "Kalimba", ofType: "wav")!)
    print(alertSound)

    try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
    try! AVAudioSession.sharedInstance().setActive(true)

    try! player = AVAudioPlayer(contentsOf: alertSound)
    player!.prepareToPlay()
    player!.play()
}

Whenever I try this, xcode throws me a fatal error when the action is triggered, saying:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Cœur
  • 37,241
  • 25
  • 195
  • 267
jacksonwelsh
  • 143
  • 9
  • You make your player an optional value. And then force-use the player? – El Tomato Oct 18 '17 at 04:21
  • Possible duplicate of [How to play a sound in Swift?](https://stackoverflow.com/questions/32036146/how-to-play-a-sound-in-swift) – mauriii Oct 18 '17 at 04:44
  • 1
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Cœur Oct 18 '17 at 05:26
  • You should not use the `!` in Swift unless you can absolutely 100% guarantee that it will never be nil at runtime. So use `?` instead, or tell us which line is giving a `nil` value when you were expecting something else with absolute confidence. – Cœur Oct 18 '17 at 05:31

1 Answers1

4

You should check with your music file is attached with your target? -

enter image description here

    let path = Bundle.main.path(forResource: "Kalimba", ofType: "wav")
    if path != nil {
        let url = URL(fileURLWithPath: path!)
        print(url)
        let player = AVPlayer(url: url)
        let playerLayer = AVPlayerLayer(player: player)
        playerLayer.frame = self.view.bounds
        self.view.layer.addSublayer(playerLayer)
        player.play()
   } else {
        print("File Not exist")
   }
Jack
  • 13,571
  • 6
  • 76
  • 98