XAML and SoundPlayer

Windows Presentation Foundation (WPF) has 3 classes that allow you to use multimedia in your applications. 

The classes are:

  • Soundplayer: Lightweight and easy to use, will run on Windows XP
  • MediaPlayer: No visual interface, cannot display videos, requires Windows Media 10 or higher
  • MediaElement: Wraps MediaPlayer and can show videos, has a video interface, requires Windows Media 10 or higher

Let’s talk about SoundPlayer:

In a WPF project (C# Express 2010 will do the job), cut and  paste the following XAML between the <Grid> and </Grid>

<Button Height="23"
               Margin="85,186,118,0"
               Name="Button1"
               VerticalAlignment="Top" Click="Button1_Click">
           <Button.Style>
               <Style>
                   <Style.Triggers>
                       <EventTrigger RoutedEvent="Button.Click">
                           <SoundPlayerAction Source="MakeASound.wav"/>
                       </EventTrigger>
                   </Style.Triggers>
               </Style>
           </Button.Style>
           <Button.RenderTransform>
           <ScaleTransform ScaleY="-1"/>
       </Button.RenderTransform> Button 1
       </Button>

In the Code behind class (usually MainWindows.XAML.cs) paste the following over the existing code:

//********************Start Paste Here**************

using System.Windows;
using System.Media;

namespace SoundplayerDemo
{
       public partial class MainWindow : Window
       {
        SoundPlayer Phaser = new SoundPlayer();
       

        public MainWindow()
        {
            InitializeComponent();
            Phaser.Play();

        }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
           
            Phaser.SoundLocation = "MakeASound.wav";

        }      
    }
}

//******End Paste here***********************

 

Or use the attached zip file.

SoundplayerDemo.zip