user3138007
user3138007

Reputation: 637

How to loop music with SKAction?

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;


}

Upvotes: 3

Views: 1117

Answers (2)

kerbi
kerbi

Reputation: 51

In iOS 9 use SKAudioNode for:

let backgroundMusic = SKAudioNode(fileNamed: "music.wav")
self.addChild(backgroundMusic)

Upvotes: 5

Andrey Gordeev
Andrey Gordeev

Reputation: 32539

You can't play background music over the scenes with using SKActions. 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];
}

Upvotes: 5

Related Questions