3

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;


}
4

2 回答 2

5

您不能使用SKActions 在场景中播放背景音乐。改用AVAudioPlayer

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];
}
于 2014-04-24T12:08:12.020 回答
5

在 iOS 9 中,将 SKAudioNode 用于:

let backgroundMusic = SKAudioNode(fileNamed: "music.wav")
self.addChild(backgroundMusic)
于 2015-11-01T09:23:16.443 回答