Partager via


Playing a Song

Demonstrates how to play a song from a user's media library.

Complete Sample

The code in this tutorial illustrates the technique for playing a song from a library. A complete code sample for this tutorial is available for you to download, including full source code and any additional supporting files required by the sample.

Download PlaySong_Sample.zip

The Albums property provides access to the media library, and the Play method plays a song. Consider any current audio playback when using the Play method. If the user currently is playing a different song, the Stop method can be used to stop the current song.

To play a song from a random album in a user's media library

The following demonstrates how to play a song from a randomly picked album (shuffle).

  1. Declare MediaLibrary and Random.

    MediaLibrary sampleMediaLibrary;
    Random rand;
    
  2. Initialize MediaLibrary and the random number generator in the game's constructor.

    sampleMediaLibrary = new MediaLibrary();
    rand = new Random();
    
  3. Stop the current audio playback by calling MediaPlayer.Stop, and then generate a random number that will serve as a valid album index. Next, play the first track in the random album.

    MediaPlayer.Stop(); // stop current audio playback 
    
    // generate a random valid index into Albums
    int i = rand.Next(0, sampleMediaLibrary.Albums.Count - 1);
    
    // play the first track from the album
    MediaPlayer.Play(sampleMediaLibrary.Albums[i].Songs[0]);
    

Concepts

  • Playing a Song from a URI
    Demonstrates how to use the MediaPlayer to play a song from a Uniform Resource Identifier (URI).
  • Media Overview
    Provides a high-level overview about the capabilities—such as playing music and video and accessing pictures—of the Media API in XNA Game Studio.

Reference