Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Sound on repeat

I have this function, that I bring to life in first scene:

    func ThemeSound() {
        if let path = NSBundle.mainBundle().pathForResource("InfinityThemeMain", ofType: "wav") {
            let enemy1sound = NSURL(fileURLWithPath:path)
            println(enemy1sound)

            var error:NSError?
            ThemePlayer = AVAudioPlayer(contentsOfURL: enemy1sound, error: &error)
            ThemePlayer.prepareToPlay()
            ThemePlayer.play()
        }
    }

but the problem is, It plays the theme just once. I need it to be played on repeat. And I thought I knew how to make this happen.

runAction(SKAction.repeatActionForever(SKAction.sequence([SKAction.runBlock(ThemePlayer), SKAction.waitForDuration(2.55)]))

But I can't paste in the ViewController, because runAction needs a child to attach it to. Any other way I could do it?

like image 369
Betkowski Avatar asked Dec 07 '14 10:12

Betkowski


1 Answers

Just set the numberOfLoops property to a negative number.

ThemePlayer.numberOfLoops = -1

From the documentation:

numberOfLoops The number of times a sound will return to the beginning, upon reaching the end, to repeat playback.

...

var numberOfLoops: Int

...

A value of 0, which is the default, means to play the sound once. Set a positive integer value to specify the number of times to return to the start and play again. For example, specifying a value of 1 results in a total of two plays of the sound. Set any negative integer value to loop the sound indefinitely until you call the stop method.

You may also need to make your AVAudioPlayer a property, rather than a local variable. As it stands, with automatic reference counting, I think your local ThemePlayer instance is likely to be deallocated by ARC. Someone who knows AVAudioPlayer better than me might be able to comment on that.

(As an aside, you might want to follow Apple's convention of naming object instances by starting with lowercase letters, e.g. themePlayer rather than ThemePlayer. It'll make your code easier for other people to read.)

like image 157
Matt Gibson Avatar answered Sep 23 '22 10:09

Matt Gibson