This documentation is archived and is not being maintained.

How To: Play a Song

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

The Complete Sample

The code in this tutorial illustrates the technique described in the text. 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.

The following example plays the first song from a randomly picked album.

The Albums property provides access to the media library, and the Play method will play a song. Consider any current audio playback when using the Play method. If the user has a different song playing currently, the user can use the Stop method to stop the current song.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace PlaySong
    public class Game1 : Microsoft.Xna.Framework.Game
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        MediaLibrary sampleMediaLibrary;
        Random rand;

        public Game1()
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

            // Frame rate is 30 fps by default for Zune.
            TargetElapsedTime = TimeSpan.FromSeconds(1 / 30.0);

            sampleMediaLibrary = new MediaLibrary();
            rand = new Random();

        protected override void Initialize()
            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


        protected override void LoadContent()
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here

        protected override void UnloadContent()
            // TODO: Unload any non ContentManager content here

        protected override void Update(GameTime gameTime)
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)

            // TODO: Add your update logic here


        protected override void Draw(GameTime gameTime)

            // TODO: Add your drawing code here