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
- Right click on your project name in solution explorer.
- Point the cursor on Add then choose Existing Item...
- Now go to the Location of your sound file and select that sound file.
- 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)
- Build the program or one time Debug the program.
- 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.
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();
}
}
}
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