播放wav文件,在项目中有相对路径

本文关键字:相对 路径 项目 wav 文件 播放 | 更新日期: 2023-09-27 18:09:36

我在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();

谢谢!

播放wav文件,在项目中有相对路径

Data目录是否在应用程序的根目录中?是否复制目录内容作为输出?

如果是这样,你是指Data'Sounds'car.wav吗?

如果从Visual Studio运行,将在[projectroot]'[release]'bin'Data'Sounds'car.wav

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

使用path . getfullpath ("relativ/path")获取文件的完整路径

您可能最好还是使用绝对路径。您可以从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;

这是为我工作

System.Media.SoundPlayer player1 = new System.Media.SoundPlayer(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"'1.wav");
   //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();