初学者使用C#编码。我构建了一个媒体播放器,允许管理员创建和保存播放列表。来宾应该能够加载播放列表并在所述播放列表上播放歌曲。不幸的是,每次访客加载创建的播放列表时,尝试播放播放列表中的任何歌曲时都会弹出错误。它似乎只加载路径细节而不是实际媒体。
“WindowsFormsApplication1.exe中发生了'System.IndexOutOfRangeException'类型的未处理异常
附加信息:索引超出了数组的范围。“
这是我所拥有的列表框下的代码:
axWindowsMediaPlayer1.URL = paths[lbPlaylist.SelectedIndex];
以下代码代码在“创建播放列表”按钮下编码:
private void btnCreate_Click(object sender, EventArgs e)
{
OpenFileDialog newPlaylist = new OpenFileDialog();
newPlaylist.InitialDirectory = "C:\\Users\\mklsingh\\Documents\\Visual Studio 2013\\Projects\\Media Player\\WindowsFormsApplication1\\Media Files";
newPlaylist.Filter = "MP3 Audio File (*.mp3)|*.mp3| Windows Media File (*.wma)|*.wma|WAV Audio File (*.wav)|*.wav|All Files (*.*)|*.*";
newPlaylist.RestoreDirectory = false;
newPlaylist.Multiselect = true;
if (newPlaylist.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
files = newPlaylist.SafeFileNames;
paths = newPlaylist.FileNames;
for (int list = 0; list < files.Length; list++)
{
lbPlaylist.Items.Add(files[list]);
}
}
}
以下代码将播放列表另存为XML文件:
private void btnSave_Click(object sender, EventArgs e)
{
StreamWriter Write;
SaveFileDialog savePlaylist = new SaveFileDialog();
savePlaylist.RestoreDirectory = false;
try
{
savePlaylist.InitialDirectory = "C:\\Users\\mklsingh\\Documents\\Visual Studio 2013\\Projects\\Media Player\\WindowsFormsApplication1\\Media Files\\Playlist";
savePlaylist.Filter = ("XML File|*.xml|All Files|*.*");
savePlaylist.ShowDialog();
Write = new StreamWriter(savePlaylist.FileName);
for (int I = 0; I < lbPlaylist.Items.Count; I++)
{
Write.WriteLine(lbPlaylist.Items[I]);
}
Write.Close();
MessageBox.Show("Playlist saved!");
}
catch //(Exception ex)
{
return;
}
}
下面的代码加载保存的XML播放列表文件:
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog loadPlaylist = new OpenFileDialog();
loadPlaylist.Multiselect = false;
this.lbPlaylist.Items.Clear();
try
{
loadPlaylist.ShowDialog();
loadPlaylist.InitialDirectory = "C:\\Users\\mklsingh\\Documents\\Visual Studio 2013\\Projects\\Media Player\\WindowsFormsApplication1\\Media Files\\Playlist";
//txtLoad.Text = loadPlaylist.Filename;
StreamReader playlist = new StreamReader(loadPlaylist.FileName);
while (playlist.Peek() >= 0)
lbPlaylist.Items.Add(playlist.ReadLine());
txtLoad.Text = loadPlaylist.FileName;
}
catch
{
return;
}
}
此外,如果用户选择一首歌并播放它,它将起作用。如果用户决定在当前播放列表中添加歌曲,则所选歌曲将不会播放并且将弹出相同的错误。如果我点击“清除列表”并选择一首新歌,它就会起作用。
请告诉我您对我的代码的看法。我仍然是初学者,我发现很难理解我在网上看到的一些代码。哈哈。只想让我的保存播放列表和创建播放列表按钮工作。感谢。
答案 0 :(得分:1)
在你做之前
xWindowsMediaPlayer1.URL = paths[lbPlaylist.SelectedIndex];
检查以确保selectedIndex实际存在于路径
中if (lbPlaylist.SelectedIndex < paths.Length)
{
xWindowsMediaPlayer1.URL = paths[lbPlaylist.SelectedIndex];
}
else
{
// Display an error?
}
这应该至少可以帮助你进行调试我建议在某处设置一个断点并检查路径的值是什么。您可能没有初始化或添加它正确,因此您尝试访问阵列中不存在的条目。