WPF 应用程序 mp3 声音文件的相对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21328664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF Application Relative path to a mp3 sound file
提问by user3231311
I'm building a WPF project with Visual Studio 2012 and I'm finding a problem with relative paths.
我正在使用 Visual Studio 2012 构建 WPF 项目,但我发现相对路径存在问题。
In the specific, I want a sound to be played when a ToggleButton is checked.
具体来说,我希望在选中 ToggleButton 时播放声音。
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:
所以我在我的根项目中创建了一个名为 Sound 的新文件夹,结构是这样的:
RehabilitationGuiProject
\Properties
\References
\Bin
\Object
\Sounds
\circles.mp3
RehabilitationGuiProject
\Properties
\References
\Bin
\Object
\Sounds \circles.mp3
... other files .xaml
... 其他文件 .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?
但是没有声音播放。哪个是从项目文件夹播放声音的正确相对路径?
回答by helb
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)
(假设您的 exe 是从 Bin/Debug 文件夹运行的)

