0

Im trying to play a random music file that loops in SpriteKit. I have achieved this but theres a delay in-between the loop using SKAction like this. Regardless of the simulator or device.

self.backgroundMusicArray = [[NSMutableArray alloc] initWithObjects:@"BackgroundMusic1.mp3",@"BackgroundMusic2.mp3",@"BackgroundMusic3.mp3",@"BackgroundMusic4.mp3",@"BackgroundMusic5.mp3",@"BackgroundMusic6.mp3", nil];

int randomNumber = arc4random() % self.backgroundMusicArray.count;

SKAction* play = [SKAction playSoundFileNamed:[self.backgroundMusicArray objectAtIndex:randomNumber] waitForCompletion:YES];

SKAction *loop = [SKAction repeatActionForever:play];

[self runAction:loop];

I have also achieved this with NSURL & AVAudioPlayer without the delay problem, but I'm lost on how to make it random. So I guess my question is "how can I do this randomly with AVAuidoPlayer". Im fairly new to objc so any help is greatly appreciated.

NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
                                     pathForResource:@"BackGroundMusic1"
                                     ofType:@"mp3"]];

self.backGroundplayer = [[AVAudioPlayer alloc]     initWithContentsOfURL:url error:nil];

self.backGroundplayer.numberOfLoops = -1;

[self.backGroundplayer play];
Jeff
  • 840
  • 10
  • 29
  • Is it possible there is any "dead air" at the start or end of the audio file? – Hasan Edain Jan 17 '16 at 21:21
  • 1
    I do note that there is a reasonable approach in this answer: http://stackoverflow.com/questions/22826675/spritekit-preload-sound-file-into-memory-before-playing – Hasan Edain Jan 17 '16 at 21:23
  • @HasanEdain I've made sure there is no dead air. Looks like that question answers it. Thank you Hasan! – Jeff Jan 18 '16 at 17:33

0 Answers0