0

i want to shuffle a dozen of songs in my game. Next song should not be the same as current song.

[[[SimpleAudioEngine sharedEngine] playBackgroundMusic: song];

There should be a loop and song should be randomized,

[[NSString stringWithFormat: @"song%i.mp3", arc4random() % 20 + 1];
//20 songs starting from song1.mp3

It would be great if the song will stop playing when the user's ipod music is playing. But the sound effect should still be available:

[[SimpleAudioEngine sharedEngine] playEffect: @"aaa.caf"]

Also, when the ipod music is playing, then launch the game, game music should not even be started.

How to implement this?

Guru
  • 21,652
  • 10
  • 63
  • 102
OMGPOP
  • 1,995
  • 8
  • 52
  • 95

1 Answers1

0

When you start your app, you can check like this and play or not your own music.

if ([[MPMusicPlayerController iPodMusicPlayer] playbackState] == MPMusicPlaybackStatePlaying) {
    // dont play and do whatever you think should be done in this case
} else {
    [[[SimpleAudioEngine sharedEngine] playBackgroundMusic: song];
}

Side note:

//Remember to preload your effects and bg music so there is not any delay
[[SimpleAudioEngine sharedEngine] preloadEffect:@"aaa.caf"];
[[SimpleAudioEngine sharedEngine] preloadBackgroundMusic:@"song1.mp3"];
//And to unload your effects when you wont use them anymore or receive a mem warning, or in dealloc
[[SimpleAudioEngine sharedEngine] unloadEffect:@"aaa.caf"];

UPDATE

In viewDidLoad, create an strings array with all your songs and shuffle them with: [self shuffle],for this implement this code:

- (void)shuffle {
    for (NSInteger i = [songsArray count] - 1; i > 0; --i) [songsArray exchangeObjectAtIndex:(arc4random() % (i+1)) withObjectAtIndex:i];
}

Every time your background music finishes use [self shuffle] and then playBackgroundMusic:[songsArray lastObject] that should take care of your shuffled playlist.

Nicolas S
  • 5,325
  • 3
  • 29
  • 36
  • what i need is to shuffle a playlist. randomly choose a new song to play after finishing current song. your code will play only one song – OMGPOP Aug 14 '11 at 06:42
  • how can i trigger -(void) shuffle when one song is done playing. – OMGPOP Aug 14 '11 at 07:09
  • Im not familiar with _SimpleAudioEngine_ you could check if there is any kind of notification you could use. – Nicolas S Aug 14 '11 at 07:11
  • There is a method called didFinishedPlaying for NSSound, but as i said, i dont know about _SimpleAudioEngine_ – Nicolas S Aug 14 '11 at 07:35
  • I just add a if-else in the shuffle, if music is not playing, then pick one song to play. then schedule your shuffle method. it works well now. – OMGPOP Sep 05 '11 at 00:03