How to play .mp3 file from resources in C#?

carck3r picture carck3r · Jul 26, 2010 · Viewed 14.1k times · Source

I put music.mp3 in resources and then I added Windows Media Player to references. I wrote this code:

WindowsMediaPlayer wmp = new WindowsMediaPlayer();
            wmp.URL = "music.mp3";
            wmp.controls.play();

It doesn't work. How can I play .mp3 file from resources?

Answer

carck3r picture carck3r · Jul 26, 2010

I did it:

WindowsMediaPlayer wmp = new WindowsMediaPlayer();
        Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PostGen.Resources.Kalimba.mp3");
        using (Stream output = new FileStream ("C:\\temp.mp3", FileMode.Create))
        {
            byte[] buffer = new byte[32*1024];
            int read;

            while ( (read= stream.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, read);
            }
        }
        wmp.URL = "C:\\temp.mp3";
        wmp.controls.play();

We have to delete this temporary file:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        File.Delete("C:\\temp.mp3");
    }