当我发布我的应用程序并运行它时,它说它找不到sound.wav
文件的路径并且它崩溃了。
我把我的声音文件放入bin/Debug/sound
文件夹,并在我的代码中像这样使用它:
public void OpenInventory()
{
SoundPlayer inventory = new SoundPlayer("sound/selection2.wav");
inventory.Play();
try
{
var item = Item.itemList.SingleOrDefault(x => x.Amount == 0);
if (item != null)
{
Item.itemList.Remove(item);
}
var loot = Loot.lootList.SingleOrDefault(c => c.Amount == 0);
if (loot != null)
{
Loot.lootList.Remove(loot);
}
}
catch
{
inter.InventoryArray();
UseItem();
}
inter.InventoryArray();
UseItem();
}
您可以将该文件作为资源嵌入,并使用资源流访问它。像这样:
strong resource name = "MyNamespace.Sound.selection2.wav";
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
var inventory = new SoundPlayer(stream);
要嵌入WAV文件,更改"Build Action"到"嵌入式资源";在解决方案资源管理器中的文件属性。
使用这种嵌入式资源的棘手之处在于找出正确的资源名称。默认情况下,它为资源使用类似名称空间的名称。例如,如果你的应用程序的默认命名空间是"MyNamespace",文件在一个名为"Sound"文件夹中,文件名为"selection2.wav",那么资源将被命名为" mynamespace.com sound .selection2.wav"
GetManifestResourceStream
: https://learn.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getmanifestresourcestream?view=netframework-4.8#system-reflection-assembly-getmanifestresourcestream(system-string)
SoundPlayer
流构造函数:https://learn.microsoft.com/en-us/dotnet/api/system.media.soundplayer.-ctor?view=netframework-4.8#system-media-soundplayer-ctor(system-io-stream)
内嵌资源名称:https://learn.microsoft.com/en-us/dotnet/core/resources/manifest-file-names