要在每次按下按钮时播放随机声音,您可以使用arc4random()
您提到的 switch 语句,每次选择不同的 mp3 文件 url - 像这样。
int random = arc4random_uniform(3);
NSString *soundName;
switch (random)
{
case 0:
soundName = @"soundone"
break;
case 1:
soundName = @"soundtwo"
break;
case 2:
soundName = @"soundthree"
break;
case 3:
soundName = @"soundfour"
break;
}
NSString *soundURL = [[NSBundle mainBundle] pathForResource:soundName ofType:@"mp3"];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundURL] error:NULL];
[player play];
为避免连续两次播放相同的声音,您可以将变量放入.h
添加一个额外的变量以保存先前生成的随机数,然后使用while()
语句确保新生成的随机数与最后一个不一样..
。H
int previousRandomNumber;
int random;
.m
random = arc4random_uniform(3);
NSString *soundName;
if(random == previousRandomNumber){
while(random == previousRandomNumber){
random = arc4random_uniform(3);
}
}
previousRandomNumber = random;
switch (random)
{
case 0:
soundName = @"soundone"
break;
case 1:
soundName = @"soundtwo"
break;
case 2:
soundName = @"soundthree"
break;
case 3:
soundName = @"soundfour"
break;
}
}
NSString *soundURL = [[NSBundle mainBundle] pathForResource:soundName ofType:@"mp3"];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundURL] error:NULL];
[player play];