Reputation: 67
I'm new to C# and I have been trying to play a sound using SoundPlayer class. So in my solution in visual studio (2015 community), I created a folder called Music and drag'n'dropped a wav file there. In properties, I found the file path and then used in the SoundPlayer constructor. Right now, it's on the desktop.
My problem is that I'll be moving the actual program (it's just console app) to another computer (with different user name...which I don't know). So is there a way C# can determine the new location (directory) for the file so that I don't get an error?
SoundPlayer spPlayer = new SoundPlayer (@"C:\Users\tvavr\Desktop\Dango\mr_sandman.wav");
spPlayer.Play();
This is the code that works. Now, how am I supposed to change that path?
Thx for your answers.
Upvotes: 1
Views: 286
Reputation: 23896
.NET has built-in tools to access locations like current user's desktop: System.Environment.SpecialFolder.Desktop
Upvotes: 0
Reputation: 801
This is a design decision that only you can answer. When you write console applications that require you to load a file, you have several options
Option #1: Have the path specified in the argument list of the program when it is executed
Assume the name of your program is playsong, you run it like this:
playsong C:/path-to-music-file/song.wav
You get the name of the song file from the argument list of Main. The first item in args is the filename:
static void Main(string[] args) {
SoundPlayer spPlayer = new SoundPlayer(args[1]);
spPlayer.Play();
}
Option #2: Access the song file by hard coded path
static void Main() {
SoundPlayer spPlayer = new SoundPlayer("C:/playsong/songs/song.wav");
spPlayer.Play();
}
Option #3: Access the song file relative to the program location
static void Main() {
SoundPlayer spPlayer = new SoundPlayer(Application.ExecutablePath + "/songs/song.wav");
spPlayer.Play();
}
If you later want to change this into a Graphical User Interface (GUI) program, you would bring up the OpenFileDialog box which lets the user choose the file.
Upvotes: 1
Reputation: 77
use dynamic path as following :
SoundPlayer spPlayer = new SoundPlayer (Application.ExecutablePath +@"\mr_sandman.wav");
where Application.ExecutablePath
will get your application folder dynamically
Upvotes: 1