我目前正在制作一个播放歌曲的应用程序。我想播放一首随机歌曲,每一个按钮被点击。我目前有:
-(IBAction)currentMusic:(id)sender {
NSLog(@"Random Music");
int MusicRandom = arc4random_uniform(2);
switch (MusicRandom) {
case 0:
[audioPlayerN stop];
[audioPlayer play];
break;
case 1:
[audioPlayer stop];
[audioPlayerN play];
break;,但我已经试过了:
- (IBAction)randomMusic:(id)sender {
NSLog(@"Random Music");
NSMutableArray * numberWithSet = [[NSMutableArray alloc]initWithCapacity:3];
int randomnumber = (arc4random() % 2)+1;
while ([numberWithSet containsObject:[NSNumber numberWithInt:randomnumber]])
{
NSLog(@"Yes, they are the same");
randomnumber = (arc4random() % 2)+1;
}
[numberWithSet addObject:[NSNumber numberWithInt:randomnumber]];
NSLog(@"numberWithSet : %@ \n\n",numberWithSet);
switch (randomnumber) {
case 1:
[audioPlayerN stop];
[audioPlayer play];
NSLog(@"1");
break;
case 2:
[audioPlayer stop];
[audioPlayerN play];
NSLog(@"2");
break;
default:
break;
}
}所有这些都有效,问题是,即使我会添加更多的歌曲,他们重复。我想要一个不会重复的随机代码。就像播放歌曲1、歌曲2、歌曲3、歌曲4和歌曲5一样,当播放时,它们都会重新启动。就像个环路。但是我现在的代码就像歌曲1,歌曲1,歌曲2,歌曲1,歌曲2,所以on...Is有什么办法不重复这些歌曲,除非所有的歌曲都已经播放了?非常感谢。
发布于 2013-11-04 13:36:42
你想要产生一个随机排列。
选项1
Hat @Alexander表示这种简单的方法..。
if(![songsToPlay count])
[songsToPlay addObjectsFromArray:songList];
int index = arc4random_uniform([songsToPlay count]);
playSong(songsToPlay[index]);
[songsToPlay removeObjectAtIndex:index];快速解释:
NSMutableArray *songsToPlay:存储这一轮尚未播放的歌曲列表。内容可以是类型:NSString,存储文件名NSNumber,存储歌曲索引
NSArray *songList:存储您想播放的所有歌曲的列表。内容应与songsToPlay类型相同。也可能是NSMutableArray。playSong(id songToPlay):停止任何当前歌曲并播放songToPlay。您需要编写这个函数,因为它取决于您的实现。选项2
使用克努斯洗牌是另一种方法:
unsigned permute(unsigned permutation[], unsigned n)
{
unsigned i;
for (i = 0; i < n; i++) {
unsigned j = arc4random_uniform(i);
permutation[i] = permutation[j];
permutation[j] = i;
}
}然后,每次您想要洗牌歌曲时都调用该函数:
int permutation[NUM_SONGS];
// I'm using a while loop just to demonstrate the idea.
// You'll need to adapt the code to track where you are
// in the permutation between button presses.
while(true) {
for(int i = 0; i < NUM_SONGS; ++i)
permutation[i] = i;
permute(permutation, NUM_SONGS);
for(int i = 0; i < NUM_SONGS; ++i) {
int songNum = permutation[i];
playSong(songNum);
}
waitForButtonPress();
}发布于 2013-11-04 13:33:42
首先,您只听到2首歌曲,因为您的randomnumber代仅限于2个值。
对于另一个问题,您可以创建一个具有随机放置轨道的可变数组,并删除每个播放元素。当计数达到0时,就开始按随机顺序播放曲目。
https://stackoverflow.com/questions/19768714
复制相似问题