我建议您有一个用于歌曲列表(库)的主容器,以及每个播放列表的容器。当然,播放列表应该指向库中的元素。
之后,有许多洗牌方法,我最喜欢的一种方法是在一个容器中拥有一个歌曲列表,您可以在其中随机挑选歌曲并删除挑选的歌曲。所以它将是随机的,但不重复播放。
我已经很久没有用 Java 编程了,所以我将给出一个 C++ 示例。我希望它简单明了:
// --*-- C++ --*--
#include <ctime>
#include <cassert>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <vector>
#include <list>
struct Song
{
std::string name;
Song (const std::string & name) :
name (name)
{
}
void play ()
{
printf ("Playing '%s'...\n", name.c_str ());
}
};
typedef std::vector<Song> Library;
typedef std::vector<Song *> Playlist;
typedef std::vector<size_t> SongIDSet;
int
main ()
{
srand (time (NULL));
Library library;
library.push_back (Song ("Lady Gaga - Bad Romance"));
library.push_back (Song ("Rihanna - Only Girl"));
library.push_back (Song ("Nelly - Just a Dream"));
library.push_back (Song ("Animal - Neon Trees"));
library.push_back (Song ("Eminem ft. Rihanna - Love The Way You Lie"));
Playlist playlist;
for (Library::iterator it = library.begin (),
end_it = library.end (); it != end_it; ++it)
{
printf ("Added song -> %s\n", it->name.c_str ());
playlist.push_back (&(*it));
}
SongIDSet shuffle;
for (size_t i = 0, end_i = playlist.size (); i < end_i; ++i)
{
shuffle.push_back (i);
}
size_t nowPlaying = 0;
while (!shuffle.empty ())
{
size_t songIndex = 0;
printf ("Shuffle? [Y/n] ");
switch (fgetc (stdin))
{
case 'N':
case 'n':
songIndex = nowPlaying + 1;
fgetc (stdin); // Skip newline.
break;
case 'Y':
case 'y':
fgetc (stdin); // Skip newline.
default:
{
printf ("Shuffling...\n");
size_t index = rand () % shuffle.size ();
assert (index >= 0);
assert (index < shuffle.size ());
songIndex = shuffle[index];
shuffle.erase (shuffle.begin () + index);
}
}
assert (songIndex >= 0);
if (songIndex < playlist.size ())
{
nowPlaying = songIndex;
playlist[nowPlaying]->play ();
}
else
{
break; // Done playing.. Repeat maybe?
}
}
}
这是一个示例运行/输出:
$ ./test
Added song -> Lady Gaga - Bad Romance
Added song -> Rihanna - Only Girl
Added song -> Nelly - Just a Dream
Added song -> Animal - Neon Trees
Added song -> Eminem ft. Rihanna - Love The Way You Lie
Shuffle? [Y/n]
Shuffling...
Playing 'Eminem ft. Rihanna - Love The Way You Lie'...
Shuffle? [Y/n]
Shuffling...
Playing 'Nelly - Just a Dream'...
Shuffle? [Y/n]
Shuffling...
Playing 'Rihanna - Only Girl'...
Shuffle? [Y/n]
Shuffling...
Playing 'Animal - Neon Trees'...
Shuffle? [Y/n]
Shuffling...
Playing 'Lady Gaga - Bad Romance'...
$ ./test
Added song -> Lady Gaga - Bad Romance
Added song -> Rihanna - Only Girl
Added song -> Nelly - Just a Dream
Added song -> Animal - Neon Trees
Added song -> Eminem ft. Rihanna - Love The Way You Lie
Shuffle? [Y/n]
S huffling...
Playing 'Nelly - Just a Dream'...
Shuffle? [Y/n] n
Playing 'Animal - Neon Trees'...
Shuffle? [Y/n] n
Playing 'Eminem ft. Rihanna - Love The Way You Lie'...
Shuffle? [Y/n] n