每个soundpack我有11个声音。它们被命名为:
我的播放器使用以下代码初始化它们:
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];
按此按钮可播放此声音。例如,我生成了4个按钮,这4个按钮每次只播放testpack1-4.mp3
,但我希望我的播放器随机播放11个声音。什么是最简单的解决方案?
注意:除非全部播放,否则我不想重复播放
答案 0 :(得分:2)
这个怎么样?
int randNum = rand() % (11 - 1) + 1;
formuale如下所示
int randNum = rand() % (maxNumber - minNumber) + minNumber;
答案 1 :(得分:2)
建议:
它将3个变量声明为静态变量,played
是一个简单的C-Array
static UInt32 numberOfSounds = 11;
static UInt32 counter = 0;
static UInt32 played[11];
如果计数器为0,则方法playSound()
将C-Array重置为零值,并将计数器设置为声音数。
调用该方法时,随机生成器会创建索引号。
如果已播放该索引处的声音,则循环直至找到未使用的索引。
- (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);
}