1. Open up Visual C# Express (or Visual Studio), and create a new Windows Form project. Name it SoundExercise.
2. Wait for the IDE to do it's loading and then click on your Form1 to select it. Press the F7 key to go into that Form1's code.
3. Add using System.Media; to the Form1's using statements. (This is so we can use the SoundPlayer class)
4. Create a SoundPlayer instance, and set the soundLocation to the ever-popular Windows "Ding" sound.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SoundPlayer My_JukeBox = new SoundPlayer(@"C:\WINDOWS\Media\ding.wav");
}
5. Go back to the design tab of your Form1 and add a Button to it from the toolBox.
6. Double click the button you just dragged. Whatever we type between those brackets in the button1.Click() event will run whenever we click the button. How cool is that!
7. Inside the click event, write this code:
private void button1_Click(object sender, EventArgs e)
{
My_JukeBox.Play();
}
8. Now every time you click on that button, the "Ding" sound will play. Pretty neat
----------------------------------------------------------------------------------------------------
But what happens when you don't want to write down a physical adress on a users machine but you instead want to use your own project resource? It's easy, and I'll show you how.
You just have to change the adress of the .wav file when instancing the SoundPlayer class!
1. Right click on your solution and "Add" a "New Item" and select a "ResourceFile". Leave the default name
2. Filter the resources by selecting Audio Files:

3. Click "Add Resource" and navigate to C:Windows:Media:tada.wav
Ok, we have a .wav file in our resources so now let's use a new SoundPlayer class with it.
4. Create a new SoundPlayer by using the following line of code.
SoundPlayer My_BetterJukeBox = new SoundPlayer(Resource1.tada);
5. Now go back to Form1 design view, and add a new button.
6. Double click the new button and program this in the Click_event:
My_BetterJukeBox.Play();
7. Now every time this button is clicked the resource .wav file will play.
This is particularly useful because now you don't have to manually type up where the resource is on your hard-drive. Only add it resources, and use it. Simple as that.
I hope you enjoyed this brief tutorial, if you have any questions please leave it in the comments area and I'll help you out.




MultiQuote







|