This works when I just call the function and play a file, however if I want to choose a random mp3 from a folder to play it stops saying “Index was outside bounds of the array”.
Can anyone spot whats wrong?
public void playrandomsound()
{
if (mp3 != null)
{
mp3.Dispose();
}
var files = new DirectoryInfo(Application.StartupPath).GetFiles(".mp3");
int index = new Random().Next(0, files.Length);
string filename = files[index].Name.ToString(); <-- App stops here
string tune = string.Concat(Application.StartupPath, "//", fiilename);
mp3 = new Audio(tune);
mp3.Play();
}
If I remove the “tostring” method on the error line, it still gives the same error.
Like Skurmedel said, you need to protect against an empty collection. But, the reason you’re having this problem is that you couldn’t ever have any .mp3 files in your collection. The other bug is here:
.GetFiles(".mp3"). You really mean.GetFiles("*.mp3").