Cowbell (Sound Effects)

0
243

Cowbell is a simple musical instrument app. With it, you can tap the screen in any rhythm, and the app makes a cowbell noise with each tap. You can even play along with songs from your music library by switching to the Music + Videos hub, starting a song or playlist, and then switching back to Cowbell. The important aspect of Cowbell is that its sole purpose is to play sound effects.

Of all the musical instruments out there, why choose a cowbell? Many people find the idea of playing a cowbell entertaining thanks to a Saturday Night Live skit in 2000 with Will Ferrell and Christopher Walken. In it, Christopher Walken repeatedly asks for “more cowbell” while Will Ferrell plays it to Blue Öyster Cult’s “(Don’t Fear) The Reaper.” With this song in your music library and this app on your phone, you can re-create the famous skit!

Playing Sound Effects

On Windows Phone, Silverlight has only one way to play audio and video: the MediaElement element. However, this element is too heavyweight for playing sound effects. When it plays, it stops any other media playback on the phone (e.g. music playing in the background from the Music + Videos hub).

The relevant XNA class is called SoundEffect, and it lives in the Microsoft.Xna.Framework.Audio namespace. To use it, you must add a reference to the Microsoft.Xna.Framework assembly in your project. In this chapter, you’ll see how to load a sound effect from an audio file and how to play it.

Using MediaElement for sound effects could cause your app to fail marketplace certification!

Because using MediaElement for sound effects results in the poor user experience of halting background media,Microsoft checks for this when certifying your app for the marketplace. If you use MediaElement for sound effects, your app will not be approved for publishing.

If you need sound effects for your app and are unable to make them yourself, here are a few good resources to check out:

  • The Freesound Project (freesound.org)
  • Partners in Rhyme (partnersinrhyme.com)
  • Soungle (soungle.com)
  • Sounddogs (sounddogs.com)
  • SoundLab, a pack of game-centric sounds from Microsoft (create.msdn.com/ en-US/education/catalog/utility/soundlab)

The User Interface

Cowbell has a main page, an instructions page, and an about page. The latter two pages aren’t interesting and therefore aren’t shown in this chapter, but Listing 30.1 contains the XAML for the main page.

LISTING 30.1 MainPage.xaml—The User Interface for Cowbell’s Main Page

[code]

<phone:PhoneApplicationPage
x:Class=”WindowsPhoneApp.MainPage”
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:phone=”clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone”
xmlns:shell=”clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone”
SupportedOrientations=”Portrait”>
<!– The application bar, with one button and one menu item –>
<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar Opacity=”.5”>
<shell:ApplicationBarIconButton Text=”instructions”
IconUri=”/Shared/Images/appbar.instructions.png”
Click=”InstructionsButton_Click”/>
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Text=”about” Click=”AboutMenuItem_Click”/>
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
<!– Just an image in a grid –>
<Grid Background=”Black” MouseLeftButtonDown=”Grid_MouseLeftButtonDown”>
<Image Source=”Images/cowbell.png” Stretch=”None”/>
</Grid>
</phone:PhoneApplicationPage>

[/code]

This is a simple page with an application bar and a grid with a cowbell image that handles taps with its MouseLeftButtonDown handler. For the sake of the cowbell image that has white edges, the grid is given a hard-coded black background. Therefore, this page looks the same under both themes except for the half-opaque application bar, as seen in Figure 30.1.

FIGURE 30.1 The main page looks identical on both dark and light themes, except for the application bar.
FIGURE 30.1 The main page looks identical on both dark and light themes, except for the application bar.

The Code-Behind

Listing 30.2 contains the code-behind for the main page. This is where all the soundeffect logic resides.

LISTING 30.2 MainPage.xaml.cs—The Code-Behind for Cowbell’s Main Page

[code]

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Resources;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Audio; // For SoundEffect
namespace WindowsPhoneApp
{
public partial class MainPage : PhoneApplicationPage
{
SoundEffect cowbell;
public MainPage()
{
InitializeComponent();
// Load the sound file
StreamResourceInfo info = Application.GetResourceStream(
new Uri(“Audio/cowbell.wav”, UriKind.Relative));
// Create an XNA sound effect from the stream
cowbell = SoundEffect.FromStream(info.Stream);
// Subscribe to a per-frame callback
CompositionTarget.Rendering += CompositionTarget_Rendering;
// Required for XNA sound effects to work
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
// Don’t let the screen auto-lock in the middle of a musical performance!
PhoneApplicationService.Current.UserIdleDetectionMode =
IdleDetectionMode.Disabled;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
// Restore the ability for the screen to auto-lock when on other pages
PhoneApplicationService.Current.UserIdleDetectionMode =
IdleDetectionMode.Enabled;
}
void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
// The screen was tapped, so play the sound
cowbell.Play();
}
void CompositionTarget_Rendering(object sender, EventArgs e)
{
// Required for XNA sound effects to work.
// Call this every frame.
Microsoft.Xna.Framework.FrameworkDispatcher.Update();
}
// Application bar handlers
void InstructionsButton_Click(object sender, EventArgs e)
{
this.NavigationService.Navigate(new Uri(“/InstructionsPage.xaml”,
UriKind.Relative));
}
void AboutMenuItem_Click(object sender, EventArgs e)
{
this.NavigationService.Navigate(new Uri(“/AboutPage.xaml”,
UriKind.Relative));
}
}
}

[/code]

  • In the constructor, the stream for this app’s .wav audio file is obtained with the static Application.GetResourceStream method.
  • The use of the CompositionTarget.Rendering event is required for sound effects to work properly. This is explained in the following warning sidebar.

When playing sound effects with XNA, you must continually call Update on XNA’s framework dispatcher!

XNA’s sound effect functionality, like some other functionality in XNA, only works if you frequently (as in several times a second) call the static FrameworkDispatcher.Update method from the Microsoft.Xna.Framework namespace.This is natural to do from XNA apps, because they are designed around a game loop that runs code every frame. (XNA even provides a base Game class that automatically does this, so developers don’t have to.) From Silverlight apps, however, which are inherently event-based, you must go out of your way to run code on a regular schedule.

To call FrameworkDispatcher.Update regularly, you could use a DispatcherTimer, as done in previous chapters.You could even use a plain System.Threading.Timer because FrameworkDispatcher.Update can be called from any thread.

However,my preferred approach is to use an event Silverlight raises before every single frame is rendered.The event is called Rendering, and it is exposed on a static class called CompositionTarget.This event is useful for doing custom animations that can’t easily be represented with Silverlight’s animation classes from Part II,“Transforms & Animations,” of this book, such as physics-based movement. In Cowbell, the event is perfect for calling FrameworkDispatcher.Update with the roughly the same frequency that an XNA app would call it. Note that the first call to FrameworkDispatcher.Update is in the page’s constructor because it takes a bit of time for the first Rendering event to be raised.

If you call Play without previously calling FrameworkDispatcher.Update within a short time span, an InvalidOperationException is thrown with the following helpful message: FrameworkDispatcher.Update has not been called. Regular FrameworkDispatcher. Update calls are necessary for fire and forget sound effects and framework events to function correctly. See http://go.microsoft.com/fwlink/?LinkId=193853 for details.

  • The code in OnNavigatedTo and OnNavigatedFrom exists to ensure that the screen doesn’t auto-lock. If the cowbell player has a long break during a performance, it would be very annoying if the screen automatically locked. And tapping the screen to keep it active isn’t a good option, because that would make an unwanted cowbell noise!
  • The sound effect is played with a simple call to SoundEffect.Play in Grid_MouseLeftButtonDown. If Play is called before the sound effect finishes playing from a previous call, the sounds overlap.

The Audio Transport Controls

When the phone’s media player plays music, this music continues playing while apps run.Users can pause, rewind, fast forward, or change songs via the 93-pixel tall top overlay that appears on top of any app when the hardware volume buttons are pressed.This functionality works great with a fun instrument app such as Cowbell. In the next release of the Windows Phone OS, due by the end of 2011, third-party apps will be able to play music in the background just like the builtin media player.

The Finished Product

Cowbell (Sound Effects)