Search code examples
c#.netwinformsaudio

absolute sound path to work in other machines


I am using the following code:

SoundPlayer soundPlay = new SoundPlayer(@"C:\more\more\Assets\Sounds\menuHoover.mp3");
soundPlay.Play();

when clicking in a button to reproduce a sound, but I have to use the absolute path to works, since I am not the only one doing working on this project, I have to use a poth comon to others too. How can I use the relative path to make this work?

I have tried diferent paths, but none seems to work. Only the absolute one.


Solution

  • You may include the file as Embedded Resource into your executable. Then there is no need to distrubute the file separately.

    To access the sound resource, use Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("<Namespace>.menuHoover.mp3"); and initialize the SoundPlayer as new SoundPlayer(stream);

    What to put in <Namespace>? Have a look in the project properties at "Default namespace". Suppose this is A.B.C. This would be the Namespace if you add the mp3 file at the root directory of the project. If you add it to a sub-directory, say X\Y\Z, the namespace would be A.B.C.X.Y.Z (special rules apply if the directory name contains characters not allowed in an identifier). See also Name of embedded resource