Reputation: 3063
I'm finishing a game for iOS done with the SpriteKit framework. I want to know if there is any way to loop background music while the user is playing. SpriteKit includes a simple music player but it does not allow looping music... So I want to know how could I accomplish this. Thanks!
Upvotes: 7
Views: 7261
Reputation: 10336
In your scene class add:
Method 1:
self.run(SKAction.repeatForever(SKAction.playSoundFileNamed("music.mp3", waitForCompletion: true)))
Method 2:
self.addChild(SKAudioNode(fileNamed: "music.mp3"))
Upvotes: 1
Reputation: 1658
You can do this in two ways.
First:
1) @import AVFoundation;
//Import this in AppDelegate file
2) @property (nonatomic) AVAudioPlayer * backgroundMusicPlayer;
//Define a property in AppDelegate file
3) under didFinishLaunchingWithOptions delegate method in AppDelegate file wrote below code
NSError *error;
NSURL * backgroundMusicURL = [[NSBundle mainBundle] URLForResource:@"bg" withExtension:@"wav"];
self.backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:backgroundMusicURL error:&error];
self.backgroundMusicPlayer.numberOfLoops = -1;
[self.backgroundMusicPlayer prepareToPlay];
4) Now you can use backgroundMusicPlayer property in any class like below code
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate.backgroundMusicPlayer play];
Second:
If you want to use SKAction Use below code
SKAction *wait = [SKAction waitForDuration:10.0];
SKAction *performSelector = [SKAction performSelector:@selector(playEffectBgSounds) onTarget:self];
SKAction *sequence = [SKAction sequence:@[performSelector, wait]];
SKAction *repeat = [SKAction repeatActionForever:sequence];
[self runAction:repeat];
-(void)playEffectBgSounds{
//Play Sound
[self runAction:[SKAction playSoundFileNamed:@"chick.mp3" waitForCompletion:NO]];
}
Upvotes: 3
Reputation: 7390
You can use AVAudioPlayer
for this purpose:
In your .h:
#import <AVFoundation/AVFoundation.h>
and add the following to interface
AVAudioPlayer *player;
In .m, initialize player with audio oath url:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:@"bg_music"
ofType:@"mp3"]];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.numberOfLoops = -1;
and when you need to play the audio, you can call:
[player play];
Note: "numberOfLoops" is the number of times that the sound will return to the beginning upon reaching the end.
Keep Coding................ :)
Upvotes: 7
Reputation: 4923
I'd rather use SKAction:
[SKAction repeatForever:[SKAction playSoundFileNamed:@"hello.caf" waitForCompletion:YES]];
or:
[SKAction repeatAction:[SKAction playSoundFileNamed:@"hello.caf" waitForCompletion:YES]
count:100];
More info at Apple Developer.
Upvotes: 4
Reputation: 25392
AVAudioPlayer *myplayer = ...
[myplayer setNumberOfLoops: INFINITY];
Upvotes: 0