A coworker and I are currently working on a simple Silverlight game for the Windows Phone 7 platform. In order to give some feedback to our end-user, we decided to add sound effects. Here is a very short post about how we did that.

The first thing is to reference the Microsoft.Xna.Framework assembly in your project. This assembly is needed to access the low-level sound component of XNA right from your Silverlight application. You also need to have your sound effect in a WAVE format file.

Then we created a simple action (from the Blend Behavior toolkit) which is a TargetedTriggerAction:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class SoundEffectAction : TargetedTriggerAction<FrameworkElement>
{
    public string Source
    {
        get { return (string)GetValue(SourceProperty); }
        set { SetValue(SourceProperty, value); }
    }
 
    public static readonly DependencyProperty SourceProperty = DependencyProperty.Register(
        "Source", 
        typeof(string), 
        typeof(SoundEffectAction), 
        new PropertyMetadata(string.Empty));
 
    protected override void Invoke(object parameter)
    {
        if(!string.IsNullOrEmpty(this.Source)
        {
            var stream = TitleContainer.OpenStream(this.Source);
            if (stream != null)
            {
                var effect = SoundEffect.FromStream(stream);
                FrameworkDispatcher.Update();
                effect.Play();
            }
        }
    }
}

Using this action, we’re able to wire sound effect right in Blend which produces the following XAML code:

1
2
3
4
5
6
7
8
<Grid Margin="2">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseLeftButtonUp">
            <Actions:SoundEffectAction Source="Resources/Sounds/Click.wav" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <!-- rest of the xaml... -->
</Grid>

Simple, isn’t it ?