Swift - Repeat audio but it plays in between?

In Swift , I play a song, it plays on viewDidLoad. It is 16 seconds long and it plays for 16 seconds. I want it to repeat itself forever. I did NSTimer

where every 16 seconds it plays a song. But it plays for 16 seconds when the app loads, stops for 16 seconds, plays, etc.

The line println("just doing some dandy debugging here.")

prints every 16 seconds.

How is it fixed?

CODE:

 //these var are created on the top of the file.
 var soundTimer: NSTimer = NSTimer()
    var audioPlayer2 = AVAudioPlayer()
 var soundTwo = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "wav"))
 //this stuff is in the viewDidLoad function.
 audioPlayer2 = AVAudioPlayer(contentsOfURL: soundTwo, error: nil)
        audioPlayer2.prepareToPlay()
        audioPlayer2.play()
 soundTimer = NSTimer.scheduledTimerWithTimeInterval(16, target: self, selector: Selector("soundTimerPlayed"), userInfo: nil, repeats: true)
    func soundTimerPlayed() {
        println("just doing some dandy debugging here.")
        audioPlayer2.stop()
        audioPlayer2.prepareToPlay()
        audioPlayer2.play()
}

      

0


source to share


1 answer


Just do it in a simple, formal way. From the property documentationnumberOfLoops

:

Specify any negative integer value to encode the sound indefinitely until you call a stop method.

But your actual problem is almost certainly due to the fact that you slow down playback a bit:

The stop method does not reset the value of the current Time 0 property. In other words, if you call stop during playback and then call playback, playback resumes where it left off.



What happens is that you stop playing the sound just before the actual end of the sample - your timer is set too short. When you first start the timer, the "game" plays a tiny amount of soft or quiet sound, which is left at the end, and then stops. The next time, currentTime was reset because the sample successfully reached the end of playback, so at the next timer interval, after 16 seconds, playback will start from the beginning. And repeat.

As Jack points out in his comment, this is why there is a delegate responder to give you a kick when playback actually ended, but I just set numberOfLoops anyway and won't bother with complicated stuff if you only need the sound to loop indefinitely.

(If you desperately want to repeat your exact timer event, then just set currentTime to 0 before replaying it.)

+2


source







All Articles