The Learner
The Learner

Reputation: 155

How to Play a Random Sound with NSArray in Cocos2d

I am trying to have a random sound play whenever the user touches the button. Here is my code so far:

-(void) playEffect {    
    NSArray *array = [NSArray arrayWithObjects:@"1.mp3", "2.mp3", "3.mp3", nil];
    int index;
    index = random() % array.count;
    sound *theSound = [array objectAtIndex:index]; 
    [theSound play];    
}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    //Blah, blah, blah

    //PLAY RANDOM SOUND
    [self playEffect];  
}

Thank you in advance for your time and assistance.

Upvotes: 0

Views: 228

Answers (1)

Morion
Morion

Reputation: 10860

You can use CocosDenshion for this. Smth like

[[SimpleAudioEngine sharedEngine] playEffect: pathToYourSoundFile];

Upvotes: 1

Related Questions