曲のリスト (ライブラリ) 用のメイン コンテナーを 1 つと、プレイリストごとにコンテナーを 1 つ用意することをお勧めします。もちろん、プレイリストはライブラリ内の要素を指す必要があります。
その後、シャッフルには多くのアプローチがありますが、私が気に入っている最良の方法の 1 つは、ランダムに曲を選択して選択した曲を削除するコンテナーに曲のリストを用意することです。したがって、ランダムですが、繰り返し再生されません。
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