title: Playing Random Audio File using Swift
body: <p>I keep on getting the following error when I use the <strong>"Shake Gesture"</strong> in the iPhone simulator:</p>
  
  <blockquote>
    <p>Fatal error: unexpectedly found nil while unwrapping an Optional value</p>
  </blockquote>
  
  <p>Here is my relevant code:</p>
  
  <pre><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: &amp;error)
  
              player.play()
          }
      }
  }
  </code></pre>
  
  <p>I have a folder named <code>sounds</code> with 4 <code>mp3</code> files located in it. The error is happening on this line of code:</p>
  
  <pre><code>  var fileLocation = NSString(string:NSBundle.mainBundle().pathForResource("sounds/" + soundFiles[randomSoundFile], ofType: "mp3")!)
  </code></pre>
  
  <p>I have tried everything I can think of to get this to work but nothing I have tried has worked. Any help is appreciated!</p>