Search code examples
iosobjective-cswiftavaudioplayernsbundle

Playing Random Audio File using Swift


I keep on getting the following error when I use the "Shake Gesture" in the iPhone simulator:

Fatal error: unexpectedly found nil while unwrapping an Optional value

Here is my relevant code:

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var soundFiles = ["kidLaughing", "pewpew", "pingas", "runningfeet"]
    var player: AVAudioPlayer = AVAudioPlayer()

    override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
        if event.subtype == .MotionShake {
            var randomSoundFile = Int(arc4random_uniform(UInt32(soundFiles.count)))
            var fileLocation = NSString(string:NSBundle.mainBundle().pathForResource("sounds/" + soundFiles[randomSoundFile], ofType: "mp3")!)

            var error: NSError? = nil

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

            player.play()
        }
    }
}

I have a folder named sounds with 4 mp3 files located in it. The error is happening on this line of code:

  var fileLocation = NSString(string:NSBundle.mainBundle().pathForResource("sounds/" + soundFiles[randomSoundFile], ofType: "mp3")!)

I have tried everything I can think of to get this to work but nothing I have tried has worked. Any help is appreciated!


Solution

  • This means that there is a value that is nil when you are asserting that it isn't. Separate the crashing line into its components and find out exactly what is nil:

    var soundFile = soundFiles[randomSoundFile]
    var path = "sounds/" + soundFile
    var fullPath = NSBundle.mainBundle().pathForResource(path, ofType: "mp3")!
    var fileLocation = NSString(string:fullPath) // fyi, this line is pointless, fullPath is already a string
    

    I would guess that it is crashing on the pathForResource line because the file cannot actually be found. Make sure you are actually linking the 'sounds' directory into your bundle.