5

I have some problems with relative paths and reproduction of wav files. I have this simple code which works perfectly:

SoundPlayer player = new SoundPlayer();
player.SoundLocation = @"C:\Users\Admin\Documents\Visual Studio 2012\Projects\TestProject\TestProject\Data\Sounds\car.wav";
player.Play();

I want somehow to play that file with relative path but I didn't have success with this:

SoundPlayer player = new SoundPlayer();
player.SoundLocation = @"Data\Sounds\car.wav";
player.Play();

Thank you!

Cristiano
  • 3,099
  • 10
  • 45
  • 67

5 Answers5

6

Is Data directory in the root directory of your application? Are you copying the directory contents as output?

If so, did you mean, Data\Sounds\car.wav?

Which, if running from Visual Studio would be in [projectroot]\[release]\bin\Data\Sounds\car.wav

If you don't see this directory in your bin folder, you'll need to ensure you're selecting all of the files you want copied to your output directory (which will copy the directory structure). You can do this by clicking on the file in your project and selecting the file as output.

George Johnston
  • 31,652
  • 27
  • 127
  • 172
2

Get the full path of your file with Path.GetFullPath("relativ/path")

Sir l33tname
  • 4,026
  • 6
  • 38
  • 49
2

You might be better off using absolute path after all. You can get the root path from the exe file, then append your relative path to it. Like this:

// getting root path
string rootLocation = typeof(Program).Assembly.Location;
// appending sound location
string fullPathToSound = Path.Combine(rootLocation, @"Data\Sounds\car.wav");
player.SoundLocation = fullPathToSound;
Greg
  • 126
  • 6
  • This doesn't work for me - Assembly.Location contains the .EXE appended to the end, so I end up with bin\Debug\Program.exe\Data\Sounds which is wrong. – Matt Sep 10 '20 at 22:21
1

This is worked for me

System.Media.SoundPlayer player1 = new System.Media.SoundPlayer(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\1.wav");
  • Thanks for your contribution. Can you [edit] your answer to explain how this fixes the original question's problem? – Mark Stewart Oct 07 '20 at 13:44
0
   //WindowsFormsApplication4.exe is name of name space this file name found in Debug file

 //you should copy your "sound.wav" into your Debug file


      string x = (Assembly.GetEntryAssembly().Location + "");
      x = x.Replace("WindowsFormsApplication4.exe", "sound.wav");
      SoundPlayer player1 = new SoundPlayer(x);
      player1.Play();