Playing a random audio file with Swift
I keep getting the following error when I use Shake Gesture in the iPhone simulator:
Fatal error: Unexpectedly found zero while expanding optional value
Here is my 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 on this line of code:
var fileLocation = NSString(string:NSBundle.mainBundle().pathForResource("sounds/" + soundFiles[randomSoundFile], ofType: "mp3")!)
I tried everything I could to get this to work, but nothing I tried worked. Any help is appreciated!
source to share
This means that there is a value that is zero when you state that it is not. Divide the fault line into your components and find out exactly what is zero:
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 assume it crashes on the pathForResource line because the file cannot actually be found. Make sure you actually link the "sounds" directory in your kit.
source to share
// You can try this also for random sound playback.
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 playPinballSound function where you want to play the random sound.
source to share