Drumming on Silverlight

A few weeks ago someone posted on their blog a simple drum kit written in Silverlight (Update: I found the original drum inspiration post here). I thought I’d give it a go as well tonight. Here’s the result:

image

(click to launch)

 

I used a few of the same tricks I’ve used before.

 

private void PlayAudio(string fileName, double volume)
{
    MediaElement me = new MediaElement();
    me.Source = new Uri(fileName, UriKind.Relative);
    me.Volume = volume;
    me.AutoPlay = true;
    me.CurrentStateChanged += new RoutedEventHandler(Audio_CurrentStateChanged);

    LayoutRoot.Children.Add(me);
}

public void Audio_CurrentStateChanged(object sender, RoutedEventArgs e)
{
    if (sender is MediaElement)
    {
        MediaElement me = sender as MediaElement;
        if (me.CurrentState == MediaElementState.Paused)
        {
            me.CurrentStateChanged -= new RoutedEventHandler(Audio_CurrentStateChanged);
            LayoutRoot.Children.Remove(me);
        }
    }
}

The kit plays multiple audio files at one time by adding (and removing) the audio streams dynamically as needed.

The ellipses are actually UserControls which use Dependency Properties to adjust to the needs of the specific drum.

private static void StandardBackgroundChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e) { Pad p = d as Pad; Ellipse playEllipse = p.FindName("playEllipse") as Ellipse; if (e.NewValue == null) { playEllipse.Fill = p.Resources["StandardBackgroundBrush"]
as Brush; } else { playEllipse.Fill = e.NewValue as Brush; } }

Even the audio file is a DependencyProperty:

public static readonly DependencyProperty AudioFileNameProperty =
    DependencyProperty.Register("AudioFileName", typeof(string),
    typeof(Pad), new PropertyMetadata(""));

The master UserControl uses eight instances of the “Pad” control like this:

<DrumPad:Pad 
    Grid.Column="1" 
    Grid.Row="1" 
    Margin="47,0,-47,0" 
    AudioFileName="/SoundEffects/Cymbal1.mp3" 
    ActivateKey="W" 
    StandardBackground="{StaticResource CymbalBrush}" 
    IsCymbal="True"/>

 

The source is here if you’re interested. If you do something cool with this … send me a link!