Home > Net >  absolute sound path to work in other machines
absolute sound path to work in other machines

Time:12-27

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.

CodePudding user response:

You have several options one is to add the location of the assets to a configuration file such as app.config

For example you could add to your app.config file:

<configuration>
 <appSettings>
  <add key="AssetPath" value="C:\\more\\more\\Assets\\Sounds\\"/>
 </appSettings>
</configuration>

Then in your code you could use something like:

string assetPath = ConfigurationManager.AppSettings["AssetPath"];
SoundPlayer soundPlay = new SoundPlayer(Path.Combine(assetPath,"menuHoover.mp3");
soundPlay.Play();

Another would be to build a path dynamically based on where your application was executed from and then build a relative path from that:

string appDirectory = AppDomain.CurrentDomain.BaseDirectory;
string assetPath = Path.Combine(appDirectory,"Assets","Sounds");
SoundPlayer soundPlay = new SoundPlayer(Path.Combine(assetPath,"menuHoover.mp3");
soundPlay.Play();

CodePudding user response:

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);

  • Related