Saturday, 25 August 2012

How to add Sound Effects, Music and Video to your Silverlight App.

Add three buttons to your Silverlight and three MediaElements control to our MainPage.xaml.

The first button is for playing music, second is for sound, and the third for video.

Copy and paste following code to MainPage.Xaml

    <Grid x:Name="LayoutRoot" Background="White">
        <Canvas Background="AliceBlue">
            <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="MySoundFile" Source="aerobics.mp3" AutoPlay="False"></MediaElement>
            <MediaElement x:Name="MymusicFile" Source="dance.mp3" AutoPlay="False"></MediaElement>
            <MediaElement Width="300" Height="300" Canvas.Top="100" x:Name="MyVideoFile" AutoPlay="False" Source="seeVideo.wmv"></MediaElement>
        </Canvas>
    </Grid>


Copy and paste following code to MainPage.Xaml.cs
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }
        private void StopAll()
        {
            MymusicFile.Stop();
            MySoundFile.Stop();
            MyVideoFile.Stop();
        }

        private void Button_Click_Music(object sender, RoutedEventArgs e)
        {
            StopAll();
            MymusicFile.Play();
        }

        private void Button_Click_Sound(object sender, RoutedEventArgs e)
        {
            StopAll();
            MySoundFile.Play();
        }

        private void Button_Click_Video(object sender, RoutedEventArgs e)
        {
            StopAll();
            MyVideoFile.Play();
        }
    }


.Play() Method will Play your Mediaelement.

.Stop() Method will Stop your Media

AutoPlay="True" will set the media in play mode by default.

No comments :