I can't seem to play an audio file in my C# .NET Windows Form programm

67 Views Asked by At

I place my audio file called MouseClick.wav under my resources folder and I have a function in code to play it.

private void playSimpleSound()
{
    SoundPlayer simpleSound = new SoundPlayer(Properties.Resources.MouseClick);
    simpleSound.Play();
}

However, when I run the programm:

    private void numPad_Click(object sender, EventArgs e)
{
    //my lines of code

    playSimpleSound();
}

I keep getting the error messages:

Exception thrown: 'System.InvalidOperationException' in System.dllAn unhandled exception of type 'System.InvalidOperationException' occurred in System.dllSound API only supports playing PCM wave files.

Then when I convert my MouseClick.wav file to PCM by using those online converter tools, I get another error message:

Exception thrown: 'System.InvalidOperationException' in System.dllAn unhandled exception of type 'System.InvalidOperationException' occurred in System.dllThe file located at C:\blank\blank\blank\42ad11c67636a47fd5ec0fc5dde8cc55.pcm is not a valid wave file.

Please advice me, I have no idea what to do. I have tried using other wav file. I tried putting my wav file at other locations.

1

There are 1 best solutions below

1
Asif Ahmed Sourav On

SoundPlayer class has some limitation. Have you tried or checked any other .NET class or libraries?

Here is an example with NAudio. Use nugget to install NAudio.

using NAudio.Wave;
private void playSimpleSound()
{
    using (var stream = new MemoryStream(Properties.Resources.MouseClick))
    {
        using (var reader = new WaveFileReader(stream))
        {
            using (var waveOut = new WaveOutEvent())
            {
                waveOut.Init(reader);
                waveOut.Play();
                while (waveOut.PlaybackState == PlaybackState.Playing)
                {
                    System.Threading.Thread.Sleep(200);
                }
            }
        }
    }
}