1

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?

Erik Godard
  • 5,930
  • 6
  • 30
  • 33

1 Answers1

1

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.

Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44
  • thank you, I've added using the SKAudioNode following @alessandro-ornano 's guide, but now the music crashes after one second of playing.. is there a way to avoid this? (it also failed to carry over from scene to scene) – Caroline Gschwend Jul 22 '16 at 14:33
  • if you want to carry over from scene to scene, you need to transfer the AudioNode over to the new scene. As for the crashing, would need more info, I am not sure what @Alessandro Omano's guide does, so I can't help in that regard.. – Knight0fDragon Jul 22 '16 at 15:35