Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sprite Kit - Keep playing audio when changing scene

I used this code to loop a audio file:

// *** In your interface... ***
#import <AVFoundation/AVFoundation.h>

...

AVAudioPlayer *testAudioPlayer;

// *** Implementation... ***

// Load the audio data
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"sample_name" ofType:@"wav"];
NSData *sampleData = [[NSData alloc] initWithContentsOfFile:soundFilePath];
NSError *audioError = nil;

// Set up the audio player
testAudioPlayer = [[AVAudioPlayer alloc] initWithData:sampleData error:&audioError];

if(audioError != nil) {
    NSLog(@"An audio error occurred: \"%@\"", audioError);
}
else {
    [testAudioPlayer setNumberOfLoops: -1];
    [testAudioPlayer play];
}

But when the scene is changed, the audio stops. Is there a way to keep it playing in the background during all scenes?

like image 556
user2255273 Avatar asked Dec 22 '25 15:12

user2255273


2 Answers

You will have set the audio player up at a level above the SKScene, I did this in one of my Sprite Kit apps by having the UIViewController play the music, then when I swapped SKScenes the music continued to play.

like image 113
fuzzygoat Avatar answered Dec 24 '25 06:12

fuzzygoat


Go to your main SKScene and add this:

[self runAction:[SKAction playSoundFileNamed:@"YourFileName.extension" waitForCompletion:NO]];

It will keep playing forever, even when you transition scenes.

Peace.

like image 28
user3504848 Avatar answered Dec 24 '25 05:12

user3504848



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!