Cozzy
Cozzy

Reputation: 1

Add sound files to build, and find path? C#

In my console based program I am wanting to use a sound file at the end of it, I was able to get that to work however when I publish the project and try send it to others I can't get it to include the sound file, how would I accomplish this?

Upvotes: 0

Views: 591

Answers (2)

Matthew Watson
Matthew Watson

Reputation: 109547

  1. Add the WAV file to your project (right-click your project in Solution Explorer, select Add | Existing Item...)
  2. In Solution Explorer go to the properties for the file you added, and for Build Action select "Embedded Resource".
  3. Add the following code to your console app:

Code:

System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream s = a.GetManifestResourceStream("<assemblyname>.<wavfilename>.wav");
SoundPlayer player = new SoundPlayer(s);
player.PlaySync();

replacing <assemblyname> with the name of your assembly, and <wavfilename> with the name of the WAV file that you added.

For my test code, that line looked like this:

System.IO.Stream s = a.GetManifestResourceStream("ConsoleApp3.tada.wav");

because my assembly name is "ConsoleApp3" and the wav file was called "tada.wav".

Note you will also need to add a using System.Media; to the source code file.

Upvotes: 1

Thomas Weller
Thomas Weller

Reputation: 59228

There are many potential solutions. One of them could be embedding the sound file as a resource.

I recommend writing an installer. Sooner or later you'll need one anyway. Maybe you have seen one of them before. It's that thing that always asks for administrator permissions and you click on the Next button until everything is installed properly.

I'd like to point you to InnoSetup, which is a free, text based installer. That's great to use with version control systems. I especially like it, because I can modify every necessary detail in my build script: just write a line of text to that file with the version number and it simply works.

It's very simple to learn and there are plenty of examples available online. The documentation is great and complete.

What you need is the [Files] section, something like

[Files]
Source: "MYPROG.EXE"; DestDir: "{app}"
Source: "MYSOUND.WAV"; DestDir: "{app}"

And then you can just access the music from the same directory as your executable.

See also the question "List of InnoSetup pages in order with parameters and screenshot" which gives you an impression of the capabilities of InnoSetup.

Upvotes: 1

Related Questions