Search code examples
c#arraysvisual-studioaudiounhandled-exception

Playing a sound from an array returns an error C# - Visual Studio


So I have a Windows Form Application in Visual Studio using C# and I have three arrays:

    System.Media.SoundPlayer[] keyClick = new System.Media.SoundPlayer[4];
    System.Media.SoundPlayer[] spaceClick = new System.Media.SoundPlayer[2];
    System.Media.SoundPlayer[] enterClick = new System.Media.SoundPlayer[1];

which when the program initialises are set to contain certain sound files:

        private void textIn_Enter(object sender, EventArgs e)
    {
        for(int i = 0; i < 4; i++)
        {
            keyClick[i] = new System.Media.SoundPlayer(@"C:\Users\brain\OneDrive\Documents\Visual Studio 2015\Projects\TextAdventure\TextAdventure\Assets\keyClick" + i + ".wav");
        }

        for (int i = 0; i < 2; i++)
        {
            keyClick[i] = new System.Media.SoundPlayer(@"C:\Users\brain\OneDrive\Documents\Visual Studio 2015\Projects\TextAdventure\TextAdventure\Assets\spaceClick" + i + ".wav");
        }

        for (int i = 0; i < 1; i++)
        {
            keyClick[i] = new System.Media.SoundPlayer(@"C:\Users\brain\OneDrive\Documents\Visual Studio 2015\Projects\TextAdventure\TextAdventure\Assets\enterClick" + i + ".wav");
        }
    }

Son now, for instance keyClick contains keyClick1.wav through to keyClick5.wav. When a key is pressed, the program plays an item at a random index from a specific array:

keyClick[randomizer.Next(0, 4)].Play();

So the first one I wrote in which is the one above works fine, however I added a command for the spacebar that plays from the spaceKey array:

spaceClick[randomizer.Next(0, 2)].Play();

However this as well as playing from the enterClick array returns an error:

"An unhandled exception of type 'System.NullReferenceException' occurred in TextAdventure.exe

Additional information: Object reference not set to an instance of an object."

I have no idea how to fix this, for all I know it should do exactly the same as playing from keyClick however it doesn't. Does anyone know how to fix this?


Solution

  • The issue is where you are filling the arrays, you are only filling keyClick.

    This is your loop for filling spaceClick

    for (int i = 0; i < 2; i++)
    {
        keyClick[i] = new System.Media.SoundPlayer(@"C:\Users\brain\OneDrive\Documents\Visual Studio 2015\Projects\TextAdventure\TextAdventure\Assets\spaceClick" + i + ".wav");
    }
    

    you are setting keyClick[i] thus overwriting the already existing ones from the previous loop. It should be changed to this

    for (int i = 0; i < 2; i++)
    {
        spaceClick[i] = new System.Media.SoundPlayer(@"C:\Users\brain\OneDrive\Documents\Visual Studio 2015\Projects\TextAdventure\TextAdventure\Assets\spaceClick" + i + ".wav");
    }
    

    Your third loop is also falling victim to the same issue, and should be changed accordingly