播放项目内相对路径的wav文件

5

我在相对路径和WAV文件的重现方面遇到了一些问题。我有这个简单的代码,它完美地运行:

SoundPlayer player = new SoundPlayer();
player.SoundLocation = @"C:\Users\Admin\Documents\Visual Studio 2012\Projects\TestProject\TestProject\Data\Sounds\car.wav";
player.Play();

我希望以相对路径的方式播放该文件,但是尝试了以下代码没有成功:

SoundPlayer player = new SoundPlayer();
player.SoundLocation = @"Data\Sounds\car.wav";
player.Play();

谢谢你!
5个回答

6

您的应用程序根目录中是否有Data目录? 您是否将该目录内容复制为输出?

如果是这样,您是指Data\Sounds\car.wav吗?

如果在Visual Studio中运行,则会在[projectroot]\[release]\bin\Data\Sounds\car.wav中找到它。

如果您在bin文件夹中看不到此目录,则需要确保选择要复制到输出目录中的所有文件(这将复制目录结构)。 您可以通过单击项目中的文件并将文件选为输出来完成此操作。


1
是的,数据在根目录中。 - Cristiano
根据你的问题中有效的文件路径来看,它并不是这样的。 - George Johnston
嗯...我通过在TestProject中右键单击项目并选择“添加新文件夹”来创建了新的Data目录。这不是根目录吗? :) - Cristiano
编译后,您的根目录是bin\Debug或bin\Release目录。 - George Johnston

2

最好使用绝对路径。你可以从exe文件中获取根路径,然后将相对路径附加到其后面。 像这样:

// getting root path
string rootLocation = typeof(Program).Assembly.Location;
// appending sound location
string fullPathToSound = Path.Combine(rootLocation, @"Data\Sounds\car.wav");
player.SoundLocation = fullPathToSound;

这对我不起作用 - Assembly.Location 包含了 .EXE 附加在末尾,所以最终我得到的是 bin\Debug\Program.exe\Data\Sounds,这是错误的。 - Matt

2

1

这对我很有用

System.Media.SoundPlayer player1 = new System.Media.SoundPlayer(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\1.wav");

感谢您的贡献。您能否[编辑]您的答案,以解释如何解决原问题的问题? - Mark Stewart

0
   //WindowsFormsApplication4.exe is name of name space this file name found in Debug file

 //you should copy your "sound.wav" into your Debug file


      string x = (Assembly.GetEntryAssembly().Location + "");
      x = x.Replace("WindowsFormsApplication4.exe", "sound.wav");
      SoundPlayer player1 = new SoundPlayer(x);
      player1.Play(); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接