Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop background music in SpriteKit

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!

like image 931
José María Avatar asked Mar 09 '14 19:03

José María


1 Answers

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.

  • A value of zero means to play the sound just once.
  • A value of one will result in playing the sound twice, and so on...
  • Any negative number will loop indefinitely until stopped.

Keep Coding................ :)

like image 153
Krishna Raj Salim Avatar answered Oct 28 '22 03:10

Krishna Raj Salim