No game is complete without a great sound track and sound effects! This tutorial will show you how to do both with a very small amount of code.
Demo:
Silverlight currently supports the following formats:
Video
Audio
To add sound, music or video you will need to declare a MediaElement. Each media file you reference must be added to your project. Select each file and change the Build Action = “Resource” in the Properties window as seen in Figure 22.1. This will ensure the media file gets copied to your ClientBin folder during execution.
Figure 22.1. Properties for the Media File
Let’s start by adding three buttons and three MediaElements to our Page.xaml. One button for playing music, one for sound, and the other for video.
<Canvas Background="Black">
<Button Click="Button_Click_Music" Canvas.Left="10" Canvas.Top="10" Width="80" Height="30" Content="Play Music"></Button>
<Button Click="Button_Click_Sound" Canvas.Left="100" Canvas.Top="10" Width="80" Height="30" Content="Play Sound"></Button>
<Button Click="Button_Click_Video" Canvas.Left="200" Canvas.Top="10" Width="80" Height="30" Content="Play Video"></Button>
<MediaElement x:Name="SoundFile" Source="Boom.mp3" AutoPlay="False"></MediaElement>
<MediaElement x:Name="MusicFile" Source="Sharon.mp3" AutoPlay="False"></MediaElement>
<MediaElement Width="300" Height="300" Canvas.Top="100" x:Name="VideoFile" AutoPlay="False" Source="MyVideo.wmv"></MediaElement>
</Canvas>
For our code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace Tip22
{
public partial class Page : UserControl
public Page()
InitializeComponent();
}
private void StopAll()
MusicFile.Stop();
SoundFile.Stop();
VideoFile.Stop();
private void Button_Click_Music(object sender, RoutedEventArgs e)
StopAll();
MusicFile.Play();
private void Button_Click_Sound(object sender, RoutedEventArgs e)
SoundFile.Play();
private void Button_Click_Video(object sender, RoutedEventArgs e)
VideoFile.Play();
Few things to notice:
Thank you, --Mike Snow Subscribe in a reader
PingBack from http://blog.a-foton.ru/index.php/2008/11/19/silverlight-tip-of-the-day-22-%e2%80%93-how-to-add-sound-effects-music-and-video-to-your-silverlight-app/