Over a million developers have joined DZone.

Make Your Windows Phone App Sing with PlaySoundAction

· Mobile Zone

Learn how to Deliver Better Mobile Apps Faster with Continuous Quality by managing the complexities of testing multiple devices and scenarios with this whitepaper from Perfecto Mobile.

Behaviors are most demanded feature to include in Silverlight, Windows Phone 7 and/or WPF applications to implement proper MVVM pattern to do some UI level actions. These are pluggable on demand and don’t need any other extra code to integrate. Just a simple XAML change and you are done.

In this article, we will learn how to use the inbuilt “PlaySoundAction” behavior to add sound effect on button click. We will demonstrate it using Windows Phone 7 application. Read more to learn. Complete demonstration with images for each steps available.

UI Design

Let us start with the application UI design. Let’s go with some buttons in the UI to give you out a simple briefing while demonstrating. First of all, we will convert the Grid named “ContentPanel” to a Stackpanel and insert some button controls as shown below:

 

1. Simple Demo UI      2. Content Panel UI Structure

 

In the second image, you will get to know how the XAML UI has been structured. No need to discuss more on the design. Here is the XAML code that we had modified just now for our demo:

<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <!--TitlePanel contains the name of the application and page title-->
    <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
        <TextBlock x:Name="ApplicationTitle" Text="Behavior Demo | Kunal's Blog" 
                   Style="{StaticResource PhoneTextNormalStyle}"/>
        <TextBlock x:Name="PageTitle" Text="Button Click Demo" Margin="9,-7,0,0" 
                   Style="{StaticResource PhoneTextTitle1Style}" FontSize="48"/>
    </StackPanel>
    <StackPanel x:Name="ContentPanel" Margin="12,0,12,0" Grid.Row="1" >
        <Button Content="Button 1"/>
        <Button Content="Button 2"/>
        <Button Content="Button 3"/>
        <Button Content="Button 4"/>
        <Button Content="Button 5"/>
        <Button Content="Button 6"/>
    </StackPanel>
</Grid>


Editing the Template

Once the UI is ready, let us edit the button template. As shown below, right click on any of the button control in the Objects and Timeline panel. From the popped up context menu, select “Edit Template” and then “Edit a Copy…”.

 

3. Editing Button Template

 

From the next dialog window that pops up in the screen, either chose a named Style or a generic style which will apply to all the button controls available in the screen or application. Let us do it for all button controls.

Select “Apply to all” and click “OK” to continue:

 

4. Create Named Style     5. Create Style and Apply to All

 

You will now see the below template structure of the button control:

 

6. Button Template

 

Go to “States” tab and click on the “Pressed” state as shown below:

 

7. Modifying the Pressed State

 

This will change the state to recording more. Now go to the “Assets” tab as shown below and click the “Behaviors” item from the left panel. This will load the behaviors available in the system. Search for “PlaySoundAction” behavior.

 

8. Adding Play Sound Behavior

 

Select the root Grid tag of the template and drag the behavior to that Grid.

 

9. Drag Behavior to the Button Template

 

From the properties panel select the sound file as shown below (make sure that, you included the sound file in the solution and built it once before coming to this screen.

 

10. Assign Sound File to the PlaySound Behavior

 

Here is the complete generated XAML code for your reference:

<Style TargetType="Button">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="{StaticResource PhoneForegroundBrush}"/>
    <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
    <Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/>
    <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiBold}"/>
    <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/>
    <Setter Property="Padding" Value="10,3,10,5"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid Background="Transparent">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="MouseLeftButtonDown">
                            <eim:PlaySoundAction Source="/Sounds/click.wav" Volume="1"/>
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="MouseOver"/>
                            <VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames 
                                            Storyboard.TargetProperty="Foreground"
                                            Storyboard.TargetName="ContentContainer">
                                        <DiscreteObjectKeyFrame KeyTime="0" 
                                            Value="{StaticResource PhoneBackgroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames 
                                            Storyboard.TargetProperty="Background"
                                            Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame 
                                            KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames 
                                            Storyboard.TargetProperty="BorderBrush" 
                                            Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame 
                                            KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames 
                                            Storyboard.TargetProperty="Foreground" 
                                            Storyboard.TargetName="ContentContainer">
                                        <DiscreteObjectKeyFrame 
                                            KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames 
                                            Storyboard.TargetProperty="BorderBrush" 
                                            Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame 
                                            KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames 
                                            Storyboard.TargetProperty="Background" 
                                            Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame 
                                            KeyTime="0" Value="Transparent"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" 
                            BorderThickness="{TemplateBinding BorderThickness}" 
                            Background="{TemplateBinding Background}" CornerRadius="0" 
                            Margin="{StaticResource PhoneTouchTargetOverhang}">
                        <ContentControl x:Name="ContentContainer" 
                                        ContentTemplate="{TemplateBinding ContentTemplate}" 
                                        Content="{TemplateBinding Content}" 
                                        Foreground="{TemplateBinding Foreground}" 
                                        HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                        Padding="{TemplateBinding Padding}" 
                                        VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

End Note

Hope this post was helpful for you to understand the behavior. “PlaySoundAction” comes by default for Windows Phone 7. If you want to play any sound file, you can easily use this behavior instead of writing a huge lines of code. This will also make sure that, you are following proper MVVM pattern.

 

Let me know, in case you need further information on this. Feedbacks are always welcome. Post your queries below, if you have. I will try to answer you as soon as possible.

 

Thanks for following my blog. If you are in Facebook, you may want to “Like” my Facebook Page. I am also available in Twitter @kunal2383.

 

 

Source: http://www.kunal-chowdhury.com/2011/11/how-to-use-playsoundaction-behavior-in.html

 

Do you know Why Apps Succeed? Perfecto Mobile analyzed over 1,000 responses to their Digial Quality Strategies survey and aim to answer the question, "Why do apps succeed?" in this exclusive report.

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}