Search code examples
c#visual-studiowinformssoundplayer

How can I play a sound that will be in the application folder?


I am trying to make that when the program initialize it plays a sound, but when I pass the installer to someone else it doesn't work since the destination is not correct in their computer.

How can I refer to the file in a way that will work in others computer?

Here is the code that I used:

public partial class Form1 : Form
{
    private SoundPlayer unacabeza = new SoundPlayer();

    public Form1()
    {
        InitializeComponent();
        unacabeza.SoundLocation = @"c:\Por_una_Cabeza_-_Carlos_Gardel_Gcxv7i02lXc.wav";
        unacabeza.Play();
    }
}

Solution

  • you can put the wav file in the Resources Folder when you do that you don't have to worry about the location or file delete by user ,you can done that by

    solution Explore > Properties > double click on Resources then a new tab will open, drag and drop your wav file into it

    and rebuild the project

    to play the wav file from the resources all you need is

    SoundPlayer test= new SoundPlayer(Properties.Resources.'filename');
    test.play();
    

    or if you just need to play the wav from the app folder you can

    • SoundPlayer test = new SoundPlayer(Application.StartupPath + "\\filename.wav");
    • SoundPlayer test = new SoundPlayer(".\\filename.wav");