1

When I publish my app and run it, it says that it couldn't find the path to sound.wav file and it crashes.

I put my sound files into a bin/Debug/sound folder, and use it like this in my code:

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();
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

1

You can embed the file as a resource and access it using a resource stream. Something like this:

strong resource name = "MyNamespace.Sound.selection2.wav";
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName);
var inventory = new SoundPlayer(stream);

To embed the WAV file, change "Build Action" to "Embedded Resource" on the file properties in solution explorer.

The tricky part of using such embedded resources is figuring out the correct resource name. By default it uses a namespace-like name for the resource. So for example, if the default namespace for your app is "MyNamespace", the file is in a folder named "Sound", and the file is named "selection2.wav", then the resource will be named "MyNamespace.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 stream constructor: https://learn.microsoft.com/en-us/dotnet/api/system.media.soundplayer.-ctor?view=netframework-4.8#system-media-soundplayer-ctor(system-io-stream)

Embedded resource names: https://learn.microsoft.com/en-us/dotnet/core/resources/manifest-file-names

Jack A.
  • 4,245
  • 1
  • 20
  • 34