Chapter 7. Let the Music Play

WHAT'S IN THIS CHAPTER?

  • Playing audio in your game with MediaPlayer

  • Working with the SoundEffect class

  • Recording and playing back audio from the device microphone

  • Saving and retrieving recorded audio to and from local storage

Every good game needs sound. XNA provides a robust Audio API that you can use to handle everything from sound effects to background music. Windows Phone 7 also includes a microphone for recording audio that you can leverage in your game.

HANDLING AUDIO

The Audio API in XNA Game Studio 4.0 provides a lot of functionality and makes using audio in your game very easy. To access the Audio API, you must include the Microsoft.XNA .Framework.Audio namespace in your code.

If you intend to load and play audio from disk, you also need to set references to the Microsoft.XNA.Framework.Content and Microsoft.XNA.Framework.Media namespaces.

Playing Music with MediaPlayer

To play music in your games, you must become acquainted with an object first. Say hello to MediaPlayer. Listing 7-1 shows an abbreviated version of the MediaPlayer class definition.

Example 7.1. The MediaPlayer Class

public static class MediaPlayer { // Determines whether the game has control of the background music. public static bool GameHasControl { get; } // Gets or set the muted setting for the media player. public static bool IsMuted { get; set; } // Gets or sets the repeat setting for the media player. public static bool IsRepeating { get; set; } // Gets or sets the shuffle setting ...

Get Professional Windows® Phone 7 Game Development: Creating Games using XNA Game Studio 4 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.