0

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?

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
blue
  • 7,175
  • 16
  • 81
  • 179
  • I think my answer in this question http://stackoverflow.com/questions/31619947/how-can-i-auto-segue-when-a-timer-finishes/31620715#31620715 can help you to control the timer properly with countdown. – Victor Sigler Oct 04 '15 at 18:50

1 Answers1

0

Get rid of the soundTrack2.numberOfLoops = 1 bit. The numberOfLoops setting is the number of times to repeat the sound. So the first time your timer fires, you queue up your sound to play twice in a row.

Then one second later, you queue up the sound to play twice in a row again.

Then, yet one second later, you queue up your sound to play another twice in a row.

If you eliminate that line, the sound will default to numberOfLoops=0, or just playing the sound once (which is what you want.)

Duncan C
  • 128,072
  • 22
  • 173
  • 272