WPF Application Relative path to a mp3 sound file
The path must be relative to the folder where your application is executed.
mplayer.Open(new Uri(@"../../Sounds/circles.mp3", UriKind.Relative));
(Assuming your exe is run from the Bin/Debug folder)
Admin
Updated on June 04, 2022Comments
-
Admin almost 2 years
I'm building a WPF project with Visual Studio 2012 and I'm finding a problem with relative paths.
In the specific, I want a sound to be played when a ToggleButton is checked.
This is the code for my button:
<ToggleButton Name="Circles" Margin="88,104,86,172" Background="#FFFFD0CD" Foreground="Black" Checked="Circles_Checked">Circles</ToggleButton>
and if I write like this:
private void Circles_Checked(object sender, System.Windows.RoutedEventArgs e) { MediaPlayer mplayer = new MediaPlayer(); mplayer.Open(new Uri("C:\\Users\\user1\\Documents\\Visual Studio 2012\\Projects\\RehabilitationGUIProject\\RehabilitationGUIProject\\circles.mp3", UriKind.Relative)); mplayer.Play(); }
everything works as espected. But I want this code to work also onto other machines, not only mine. And what If I have to move the sounds to another location? I would like to use relative paths and move every sound inside my project folder.
So I created a new folder named Sound inside my root project, the structure is like this:
RehabilitationGuiProject
\Properties
\References
\Bin
\Object
\Sounds \circles.mp3... other files .xaml
So I wrote the same lines of code above, changing this one:
mplayer.Open(new Uri(@"/Sounds/circles.mp3", UriKind.Relative));
But no sound is played. Which is the correct relative path for playing sounds from a project folder?
-
Admin over 10 yearsThank you, now it's working! I really appreciated the help!
-
metatron almost 3 yearsInstead of jumping out of the Debug folder (by prepending ../../) you can mark the mp3 file as "Content" and "Copy if newer" in the Visual Studio Solution Explorer. Visual Studio will then copy the mp3 file to the correct location.