Search code examples
c#builduripack-uri

c# have sound files in build


I need to make a game for school.

I was adding some sound effects and music.

I have the paths to the .wav in the class and it will play them, but only when I start the game from the bin map in the project. I figgered out that the files are not included inside off the build. I started looking for it but could not find the correct way for it.

I have:

MediaPlayer _musicPlayer = new MediaPlayer();
string s = System.IO.Packaging.PackUriHelper.UriSchemePack;
Uri uri = new Uri(@"pack://application:,,,/{Assembly name};component/Resources/Sounds/Music/Main_theme_-_Thiago_Adamo.wav")
_musicPlayer.Open(uri);
_musicPlayer.Play();

This however does not work. If I add an messagebox with:

uri.IsFile.ToString()

It displays false.

On the file I set the propeties to be:

Build Action: Resource

Copy To Output Directory: Copy Always

I hope someone can help me.


Solution

  • Add the files to the project in your solution in Visual Studio, so they show up in the Solution Explorer (docked on the right side of the VS window by default). Click on a file so you see the properties window for that file (shown below the Solution Explorer in VS by default). Make sure the Copy to Output Directory property is set to either Copy Always or Copy if newer, and the Build Action is set to Content. Do this for each sound file you need.

    At this point, the files will be copied to same folder as your application when you build it. They will not be packaged. They'll just be there in the file system next to your program. If you build the application in Debug mode, this is in the /bin/Debug folder (by default) for your project. If it's Release mode, it's the /bin/Release folder, but as long as your working directory matches your application you can reference them in the Uri by file name alone (otherwise you'll need to check the application path and build the full path to the file).

    The reason you need Content instead of Resource is in the Remarks section of the MediaPlayer class documentation:

    When distributing media with your application, you cannot use a media file as a project resource. In your project file, you must instead set the media type to Content and set CopyToOutputDirectory to PreserveNewest or Always.