目前我正在尝试制作一款MP3播放器。我有一个名为'随机播放歌曲的复选框'。还有一个充满歌曲的列表框。我的问题是,如果选择一次,我不想播放同一首歌。我该怎么做呢? 我使用以下代码:
Random rnd = new Random()
private void btnnext_Click_1(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
int number = rnd.Next(0, listBox1.Items.Count - 1);
listBox1.SelectedIndex = number;
play();
}
最后一件事:如果选中复选框,我就无法选择列表框的最后一个索引。它从不选择最后一个索引。我该如何解决这个问题?
答案 0 :(得分:0)
执行此操作的一种方法是获取所有歌曲索引(0 - > song.Count - 1),将它们随机播放,然后按顺序播放歌曲。
例如:
private static void Main()
{
// Pretend this is your list of songs
var orderedListOfSongs = new List<string>
{
"song one",
"song two",
"song three",
"song four",
"song five",
"song six",
"song seven",
"song eight",
"song nine",
"song ten",
};
// Generate a new list of ints representing the index of each song and shuffle them
// Note: There are better ways to shuffle a list, this is just for an example
var rnd = new Random();
var randomizedIndexes = Enumerable.Range(0, orderedListOfSongs.Count)
.OrderBy(i => rnd.NextDouble())
.ToList();
for (int i = 0; i < orderedListOfSongs.Count; i++)
{
Console.WriteLine($"Now playing: {orderedListOfSongs[randomizedIndexes[i]]}");
}
GetKeyFromUser("\nDone! Press any key to exit...");
}
<强>输出强>