brux
brux

Reputation: 3230

Playing Random mp3 file unkown error

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.

Upvotes: 1

Views: 247

Answers (2)

mattmc3
mattmc3

Reputation: 18335

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").

Upvotes: 3

Skurmedel
Skurmedel

Reputation: 22149

The ToString is not your problem, you are trying to access a position in the array that doesn't exist.

I don't know what your array contains in your test runs, but I see a possible culprit. What if files is empty and length is zero; meaning no files were found? You will get 0 from the random number generator and try to access position zero in a empty array.

This is of course easily avoided by checking if files.Length < 1 (or files.Length == 0) and bail if so.

Upvotes: 1

Related Questions