Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Add Sound File into Resource and Access It in .NET (C#)

0.00/5 (No votes)
20 Jan 2011 1  
How we can access sound file from resource, not from any other location

Introduction

Actually, in this article, I am accessing the sound file from our project resource. Many times, we use sound in our project but in earlier days, I placed the sound file in a different location and then I access it. It's useful for those who want to hide resource of project and they want to make the project portable.

Using the Code

  1. Right click on your project name in solution explorer.
  2. Point the cursor on Add then choose Existing Item...
  3. Now go to the Location of your sound file and select that sound file.
  4. Now select your sound file in solution explorer, then Right click on it, choose Properties and change its Build Action property (Content to Embedded Resource)
  5. Build the program or one time Debug the program.
  6. Now if you want to play sound file when a particular Form is loaded, then use the given code in Form_Load event.
    NOTE: In this code, Dreamer.wav is the name of the sound file.

Step_1_2.JPG

//
// Any source code blocks look like this
//
using System.Reflection;
using System.IO;
using System.Resources;
using System.Media;
using System.Diagnostics;
 
namespace Yournamespace
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
 
        private void Form2_Load(object sender, EventArgs e)
        {
            Assembly assembly;
            Stream soundStream;
            SoundPlayer sp;
            assembly = Assembly.GetExecutingAssembly();
            sp = new SoundPlayer(assembly.GetManifestResourceStream
				("Yournamespace.Dreamer.wav"));
            sp.Play();  
        } 
    }
}

/*SoundPlayer sp = new SoundPlayer
(global::WindowsApplication1.Properties.Resources.yoursoundfilename); */

Points of Interest

Now, the time is 1:57 am, so I have to go. Actually, there are also some other techniques to access the sound file from resource. I just give one example for this which is mentioned in the above code in the comments.

History

  • 20th January, 2011: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here