I want to loop my background music with an SKAction but the music stops after one row when I switch to an other scene. Is there a way to start the loop and keep playing it over different scenes?
Right now the code is placed in the init method of MyScene - is that the correct place? Maybe didFinishLaunchingWithOptions?
Here is what I've tried:
if (delegate.musicOn == YES && delegate.musicIsPlaying == NO) {
SKAction *playMusic = [SKAction playSoundFileNamed:@"loop.wav" waitForCompletion:YES];
SKAction *loopMusic = [SKAction repeatActionForever:playMusic];
[self runAction:loopMusic];
delegate.musicIsPlaying = YES;
}
You can't play background music over the scenes with using SKAction
s. Use AVAudioPlayer
instead:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"music" ofType:@"mp3"];
NSError *error;
AVAudioPlayer *gameSceneLoop = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:filePath] error:&error];
if (error) {
NSLog(@"Error in audioPlayer: %@", [error localizedDescription]);
} else {
gameSceneLoop.numberOfLoops = -1;
[gameSceneLoop prepareToPlay];
[gameSceneLoop play];
}