5

I'm trying to play a specific sound. However I can't seem to reach the file that I added in my Solution Explorer. (I have this folder called "Sounds/" with several .wav-soundeffects in it)

When I hardcode a filepath to a random fixed location on my HDD it works just fine. Also when I put my resources in my "bin/debug/"-folder it works just fine (this is the closest I got to a working relative path with the AppDomain.CurrentDomain.BaseDirectory function).

How can I make my SoundPlayer work when using the files I added in my Solution Explorer?

dcastro
  • 66,540
  • 21
  • 145
  • 155
Totumus Maximus
  • 7,543
  • 6
  • 45
  • 69

2 Answers2

4

You could embed them as a project resource on the dll/exe and then use them through the Application object:

Adding and Editing Resources (Visual C#)

http://msdn.microsoft.com/en-us/library/7k989cfy%28v=vs.90%29.aspx

You could also use the Resource Manager (better option if you want to have your sound files delivered separately):

Resource Manager

http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager%28v=vs.110%29.aspx

Rafa
  • 2,328
  • 3
  • 27
  • 44
  • Ah, this embedding really seemed to do the trick here. After a bit of management it is pretty easy to handle. I wonder however why they can't be reached from the solution explorer directly. – Totumus Maximus Feb 28 '14 at 10:16
  • Probably you have Java experience and you're used to jars and so on. In .net you work with dll and the process is different. But you're right, it could be easier. – Rafa Feb 28 '14 at 13:11
  • Yeah, I've been using Java for like 12 years now and I had to use C# to a more extensive extent just recently. Documentation seems a bit harder to get for C# then Java, but that might just be me. – Totumus Maximus Feb 28 '14 at 13:46
3
System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav");
player.Play();

or You can embed the sound files into your project using resources.

System.Media.SoundPlayer player = new System.Media.SoundPlayer(Resources.Yourfile);
player.Play();

Update: When you add a sound file to the Resources, you can access it by the name of the file.

Mihai Hantea
  • 1,741
  • 13
  • 16