I'm working in Swift and I have an NSTimer that counts down from 3, 2, 1. I want to play an audio file every time this timer decrements, so that the timer would show 3 and the audio would play once, then it flips to 2 and the audio plays once, finally it goes to 1 and it plays once.
This is how I've created the timer and tried to do that:
var path2 = NSBundle.mainBundle().pathForResource("splatter1", ofType: "wav")
var soundTrack2 = AVAudioPlayer()
func timeToMoveOn() {
let loadingDelay = 0.01 * Double(NSEC_PER_SEC)
let loadingTime = dispatch_time(DISPATCH_TIME_NOW, Int64(loadingDelay))
dispatch_after(loadingTime, dispatch_get_main_queue()) {
//After delay
self.performSegueWithIdentifier("goToGameScene", sender: self)
}
}
func splatterSound() {
soundTrack2 = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path2!), error: nil)
soundTrack2.numberOfLoops = 1
soundTrack2.volume = 0.35
soundTrack2.play()
}
func updateCounter() {
countdownTestLabel.text = String(counter--)
splatterSound()
if counter == 0 {
countdown.invalidate()
//Then trigger segue to Game Scene view
timeToMoveOn()
}
}
In view did load:
counter = 3
countdown = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)
My problem is that the audio file plays every time the timer decrements, but it plays multiple times. For example it will one time, then a second time, then a third fourth and fifth time all in rapid succession. It shouldn't do that.
How can I fix this so that it only plays when the timer decrements?