声音随机化最简单的方法是什么
问题描述:
我对每个声音包有11个声音。它们被命名为:声音随机化最简单的方法是什么
- testpack1.mp3,
- testpack2.mp3等。
我的球员,此代码初始化它们:
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种声音中随机选取。什么是最简单的解决方案?
注:我不想重复播放MP3,除非所有播放
答
这个怎么样?
int randNum = rand() % (11 - 1) + 1;
的formuale就像下面
int randNum = rand() % (maxNumber - minNumber) + minNumber;
答
你有没有尝试过这样的:
NSUInteger value = arc4random(11) + 1;
或
NSUInteger value = arc4random_uniform(11) + 1;
(iOS版> 4.3)
这会给你一个介于0和10之间的随机数,然后加1.因此你的文件将从yourString1到yourString11。
答
一个建议:
它声明3个变量为静态变量,played
是一个简单的C-阵列
static UInt32 numberOfSounds = 11;
static UInt32 counter = 0;
static UInt32 played[11];
如果计数器playSound()
将C-Array对零个值的方法,0和将计数器设置为声音的数量。 当调用该方法时,随机生成器会创建一个索引号。
- 如果该索引在数组中的值为0,则播放声音,设置数组中的索引并减少计数器。
-
如果该索引处的声音已播放完毕,则循环播放直到找到未使用的索引。
- (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); }
没错,和在代码的发布问题第一线,以从randNum此答案替换值+ 1。 – Bamsworld
谢谢,但我忘了说,每个声音应该只采取一次... – iOSBeginner
@iOSBeginner:好的...创建一个已完成的数字数组,并检查该数字是否已完成,再次调用randNum ..而已... –