سؤال

I'm writing a program to play audio from a Resources folder located in the same directory as my application (so it can be moved to a different computer) using the Windows Media Player component.

My current code to select the audio clip is:

soundPlayer.URL = @"C:\Users\Ryan\Desktop\MyProgram\SFX\nameThatTune.mp3";

Which works fine, but when I change it to:

soundPlayer.URL = @"SFX\showIntro.mp3";

It stops working. I've also tried beginning the file path with ~/ and ../, but neither work. Is this a problem specific to the WMP Component or am I missing a bigger problem?

هل كانت مفيدة؟

المحلول

Relative paths depend on the value of Environment.CurrentDirectory. When you run the application inside Visual Studio, the current directory points to your project's root folder (not the application's executalbe path). Also some operations can change the current directory (opening a file using OpenFileDialog). You can't always rely on the current directory to be a specific place, so you should alwasy try to use absolute path.

If the file is in the applications folder (near the .exe file), you can use:

soundPlayer.URL = Path.Combine(
    Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
    "showIntro.mp3");

or if you are on WinForms:

soundPlayer.URL = Path.Combine(
    Path.GetDirectoryName(Application.ExecutablePath),
    "showIntro.mp3");

Changing it to point to a sublfolder is also straightforward.

Notice that the file must in the output folder of your project (bin\Debug for example).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top