XNA Object for Creating a Collection of Songs / Playlist
Playing a song with XNA 3.0 using the MediaPlayer object is easy but playing a collection of songs (a playlist as it is often called) isn't quite as straightforward. Unfortunately there is no built in method for creating a playlist so it forces the developer to create their own methods for handling multiple songs and for playing the next song when the first one completes.
Below I have created a music collection class that is largely a wrapper for the MediaPlayer object first introduced in XNA 3.0 which you can use to call most of the useful MediaPlayer features. The major improvement is that you can add multiple songs to this collection and it will play through them all. I have hacked this out of my game but I believe it should work as is (or at least with only minor modifications, please let me know in the comments below if that is the case).
In order to use this class, you must first create an instances of the object (which you have to pass a ContentManager object to). Then add a call to the Play() method of this object in your game's Update() method. Each time Update() is done, the status of the current song will be checked and the next song will be played when the previous song completes.
class Music : System.Collections.ObjectModel.Collection<Song>
{
private int nextSong;
private MediaState previousMediaState;
public Music(ContentManager content)
{
// Setup music player
MediaPlayer.IsRepeating = false;
MediaPlayer.IsShuffled = false;
MediaPlayer.Volume = .25f;
previousMediaState = MediaState.Playing;
nextSong = 0;
}
public void Play()
{
if ((MediaPlayer.State == MediaState.Stopped) && (previousMediaState == MediaState.Playing))
{
Song currentSong = this.Items[nextSong];
MediaPlayer.Play(currentSong);
nextSong++;
if (nextSong > this.Count - 1)
{
nextSong = 0;
}
}
previousMediaState = MediaPlayer.State;
}
public void AddSong(Song newSong)
{
this.Add(newSong);
}
public void Stop()
{
MediaPlayer.Stop();
}
public void Pause()
{
MediaPlayer.Pause();
}
public void Resume()
{
MediaPlayer.Resume();
}
}
The reason the Play() method checks both the current and previous state of MediaPlayer is because even though you tell a song to play, it takes several loops through your game before the MediaState is set to Playing. Because of this, your song will just continually be started over and over and never reach the Playing state. This might run fine on your PC, but it will cause your game to black screen when running on your Xbox. Also of note, Microsoft recommends using an event driven model to determine when it is time to change songs. Certainly this would work just as well but I felt this way was a little bit easier to follow.
Some improvements to this code would be to add a Remove function to remove songs from the collection (make sure to also modify the nextSong value when doing<
This article has been view 3457 times.
|