Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!
Windows Phone Zone is brought to you in partnership with:

Kunal Chowdhury is a Microsoft MVP (Most Valuable Professional) in Silverlight Technology, a Codeproject MVP & Mentor, DZone's MVB (Most Valuable Blogger), Speaker in various Microsoft events, Author, passionate Blogger and a Software Engineer by profession. He shares his technical findings in his Blog: http://www.kunal-chowdhury.com His other website: http://www.silverlight-zone.com He is also available in Twitter: http://www.twitter.com/kunal2383 Kunal is a DZone MVB and is not an employee of DZone and has posted 14 posts at DZone. You can read more from them at their website. View Full User Profile

Make Your Windows Phone App Sing with PlaySoundAction

02.06.2012
Email
Views: 1110
  • submit to reddit
It's so easy to get up and running with your first Windows Phone app!  Just pick up the FREE toolkit from Microsoft, register at AppHub, and start checking out some fundamental tutorials.

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

 

Published at DZone with permission of Kunal Chowdhury, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

The Windows Phone Microzone, which is supported by Microsoft, is your one-stop-shop for news, tutorials, perspectives, and research on the mobile platform that is making waves in smartphone ecosystem.

Comments

Paul Shezier replied on Fri, 2012/04/13 - 3:23pm

I have followed through this article on adding a sound to a button but for some reason no sound is produced when I tap the button. I wanted to use a .wma file but have tried a .wav as per your example. I have even copied in you xaml but still no sound.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.