Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 926
three3 Avatar asked May 16 '26 12:05

three3


2 Answers

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.

like image 66
drewag Avatar answered May 19 '26 02:05

drewag


//You can try this one also for random sound play.

import UIKit
import AVFoundation
class GameScene: SKScene {
var pinballVoiceArray = ["BS_PinballBounce1.mp3", "BS_PinballBounce2.mp3", "BS_PinballBounce3.mp3"]
var randomIndex = 0
override func didMoveToView(view: SKView) {
    //use the random sound function
    playPinballSound()
   }
func playPinballSound () {
    randomIndex = Int(arc4random_uniform(UInt32(pinballVoiceArray.count)))
    var selectedFileName = pinballVoiceArray[randomIndex]
    runAction(SKAction.playSoundFileNamed(selectedFileName, waitForCompletion: false))
    }
}

// Call the Function playPinballSound where you would like to play random sound.

like image 34
Raksha Saini Avatar answered May 19 '26 02:05

Raksha Saini