c# 在构建中有声音文件

c# have sound files in build

我需要为学校制作一个游戏。

我正在添加一些音效和音乐。

我在 class 中有 .wav 的路径,它会播放它们,但只有当我从项目中的 bin 映射开始游戏时。我发现这些文件不包含在构建中。我开始寻找它,但找不到正确的方法。

我有:

MediaPlayer _musicPlayer = new MediaPlayer();
string s = System.IO.Packaging.PackUriHelper.UriSchemePack;
Uri uri = new Uri(@"pack://application:,,,/{Assembly name};component/Resources/Sounds/Music/Main_theme_-_Thiago_Adamo.wav")
_musicPlayer.Open(uri);
_musicPlayer.Play();

但这不起作用。如果我添加一个消息框:

uri.IsFile.ToString()

显示为false。

在文件中,我将属性设置为:

构建操作:资源

复制到输出目录:始终复制

希望有人能帮助我。

将文件添加到 Visual Studio 解决方案中的项目,以便它们显示在解决方案资源管理器中(默认停靠在 VS window 的右侧)。单击一个文件,以便您看到该文件的属性 window(默认情况下显示在 VS 中的解决方案资源管理器下方)。确保 Copy to Output Directory 属性 设置为 Copy AlwaysCopy if newer,并且 Build Action 设置为 Content。为您需要的每个声音文件执行此操作。

此时,当您构建应用程序时,文件将被复制到与您的应用程序相同的文件夹中。 它们不会被打包。它们只会在您的程序旁边的文件系统中。如果您在调试模式下构建应用程序,则它位于项目的 /bin/Debug 文件夹中(默认情况下)。如果它是 Release 模式,它是 /bin/Release 文件夹,但只要你的工作目录与你的应用程序匹配,你就可以在 Uri 中单独通过文件名引用它们(否则你需要 check the application path 并构建文件的完整路径)。

您需要 Content 而不是 Resource 的原因在于 Remarks section of the MediaPlayer class documentation:

When distributing media with your application, you cannot use a media file as a project resource. In your project file, you must instead set the media type to Content and set CopyToOutputDirectory to PreserveNewest or Always.