And…we’re back. That might be the longest span of time I’ve gone without blogging in quite a while. Anyways, I’m going to pretend like we never stopped this little series I’m calling the 31 Days of Silverlight, and we’ll continue down the path.
Today we’re going to be discussing how to add a sound to a button click. This activity translates to nearly any event in your Silverlight application, but for simplicity’s sake, we’ll stick with the standard button click. So, let’s get started…
1. Find a sound effect.
I found my sound effects at a site called Sound Jay. He offers a whole pile of different sound effects for free, and they’re pretty good. They are offered in .WAV and .MP3, so make sure to download the MP3 version of the sound effect you choose.
2. Add the sound to your ClientBin.
You don’t HAVE to do this, but I recommend using this method over packaging your sound effects directly into the .XAP file. Your application will load faster, and your files will actually be less likely to be “borrowed.” To add it, choose “Add > Existing Item…” from the Solution Explorer in Visual Studio.
3. Add a MediaElement to your XAML page.
This MediaElement tag will be the container that holds our audio file. Here’s the code for my tag:
<MediaElement x:Name="Beep" Source="beep-7.mp3" AutoPlay="False" />
4. We also need a button.
Nothing special about it, but for this example, we’ll need a button on our page. Here’s the code for that:
<Button Click="Button_Click" x:Name="Button" Width="100" Height="100" Content="Beep!" />
5. Hook up the event handler.
In the codebehind, we need one line of code. Here it is:
After that, we’re done, right? Wrong. Following the above instructions gets you close, but if you run your application, you’ll notice that only the first “click” of your button works, and after that, nothing. Thankfully, we’re 90% of the way to the “correct” way to handle this. Here’s what we need to do to make this work EVERY time we click the button:
6. Define the source in code.
We are going to remove the Source property from our MediaElement tag. By defining this each time we click the button, we create a new instance of the file. This means that if you have a longer audio file (> 1 second), the audio will start over each time the button is clicked. Here’s the code in our event handler now:
Beep.Source = new Uri("beep-7.mp3", UriKind.Relative);
You should now find that your button click results in your sound effect each time. If you chose a longer sound effect (>1 second), you should also find that the sound effect will stop and start over if you click the button a second time before the sound completes. This is because we are destroying that instance of the sound, and creating a new one on each click.
Tune in tomorrow for another exciting episode of the 31 Days of Silverlight!