Reputation: 103
I have 11 sounds for each soundpack. They are named:
My player initialises them with this code:
NSString * strName = [NSString stringWithFormat:@"testpack%ld", (long) (value+1)];
NSString * strPath = [[NSBundle mainBundle] pathForResource:strName ofType:@"mp3"];
NSURL * urlPath = [NSURL fileURLWithPath:strPath];
self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlPath error:NULL];
This sounds will be played by pressing buttons. For example, I have generated 4 buttons, this 4 buttons play every time only testpack1-4.mp3
but I want that my player takes random out of the 11 sounds. What's the easiest solution?
Note: I don't want to repeat the mp3 unless all are played
Upvotes: 2
Views: 56
Reputation: 285160
A suggestion:
It declares 3 variables as static variables, played
is a simple C-Array
static UInt32 numberOfSounds = 11;
static UInt32 counter = 0;
static UInt32 played[11];
The method playSound()
resets the C-Array to zero values if the counter is 0 and sets the counter to the number of sounds.
When the method is called the random generator creates an index number.
If the sound at that index has been played yet, loop until a non-used index is found.
- (void)playSound
{
if (counter == 0) {
for (int i = 0; i < numberOfSounds; i++) {
played[i] = 0;
}
counter = numberOfSounds;
}
BOOL found = NO;
do {
UInt32 value = arc4random_uniform(numberOfSounds) + 1;
if (played[value - 1] != value) {
NSString * strName = [NSString stringWithFormat:@"testpack1-%d", value];
NSString * strPath = [[NSBundle mainBundle] pathForResource:strName ofType:@"mp3"];
NSURL * urlPath = [NSURL fileURLWithPath:strPath];
self.audioplayer = [[AVAudioPlayer alloc] initWithContentsOfURL:urlPath error:NULL];
played[value - 1] = value;
counter--;
found = YES;
}
} while (found == NO);
}
Upvotes: 2
Reputation: 31647
How about this?
int randNum = rand() % (11 - 1) + 1;
The formuale is like below
int randNum = rand() % (maxNumber - minNumber) + minNumber;
Upvotes: 2