Caroline Gschwend
Caroline Gschwend

Reputation: 11

SpriteKit background music not looping forever

I'm making a simple SpriteKit game with two scenes, and I want the background music to loop unconditionally through both scenes. Right now, I'm using

if soundIsPlaying == false {
   runAction(SKAction.repeatActionForever(backgroundMusicEffect), withKey: "backgroundMusic")
   soundIsPlaying = true
}

in my menu scene where backgroundMusicEffect is a global variable

let backgroundMusicEffect = SKAction.playSoundFileNamed("content/divertimentoK131.mp3", waitForCompletion: true)

When I play my game, the music never loops. It always stops after one play. If I remove the if-else statement, the music plays over itself every time I reenter the menu.

Is there a better way to play background music? What am I doing wrong?

Upvotes: 1

Views: 552

Answers (1)

Knight0fDragon
Knight0fDragon

Reputation: 16827

I believe that the way you are doing it, after the first time looping, every iteration after is "complete" since the sound is finished. You would need to create a new SKAction instance every time if you want to get this to loop.

This of course is a bad idea, since playSoundFileNamed is designed to only play a sound file once with as little over head as possible.

As @Alessandro Omano has commented, use SKAudioNode to get sound playing in a loop. This is my preferred way of doing in, but you limit yourself to >= iOS 9 users.

If you have to support iOS 8 users (At this point I would say why bother) then you need to look into the AVFoundation sections of the libs to get audio going, or use OpenAL.

Upvotes: 1

Related Questions