How to reference an audio resource from C# in Windows Forms?

81 Views Asked by At

I have a .resx with various sounds like "pulse". The problem is when I reference it in the code:

using (SoundPlayer soundPlayer = new SoundPlayer((Properties.Resources.correct_config))
{
    soundPlayer.Play();
}

In Properties.Resources.correct_config, I get the following exception:

System.Runtime.SeriaIization.SeriaIizationException: 'Type 'System.lO.MemoryStream' in Assembly 'System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' is not marked as serializable.'

It has nothing to do with the soundplayer, the problem is that line. I have also tried declaring the class as [Serializable]. I would appreciate any advice. Thank you!

1

There are 1 best solutions below

0
Mustafa Özçetin On

Your SoundPlayer code seems correct. The problem is clearly with the project resource, namely correct_config. Please make sure that you have this resource by looking at your project's Resources panel. For this right click your project, click Properties and select the Resources tab on the left. If it is here it might be corrupted. If this is the case deleting and re-adding it to the resources may resolve the issue. Also check that your sound file is valid and it plays with Media Player etc.

To test whether your code executes, I have added a new sound resource (C:\Windows\media folder includes some *.wav files) to my project resources by dragging the source file, Alarm.wav for example to the Resources panel. Then I can get the sound file as a Stream and play it like

Stream soundStream = Properties.Resources.Alarm;
using (var soundPlayer = new SoundPlayer(soundStream))
{
    soundPlayer.Play();
}

If you are not familiar with project resources, there is a similar post explaining the steps to add and use an image resource. Just apply the steps for your sound file.