Play a sound using SoundPlayer
Asked Answered
P

2

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?

Pagel answered 28/2, 2014 at 9:33 Comment(0)
G
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

Goodhen answered 28/2, 2014 at 9:35 Comment(3)
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.Pagel
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.Goodhen
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.Pagel
N
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.

Necolenecro answered 28/2, 2014 at 9:37 Comment(3)
The first one I have confirmed that it works. However I would like the second option. I can't seem to reach 'Resources.Yourfile'. Can you elaborate this?Pagel
When you add a sound file to the Resources, you can access it by the name of the file.Necolenecro
Ah well, this seems to work but after I embedded it in the way that was linked in the other answer.Pagel

© 2022 - 2024 — McMap. All rights reserved.