Creating Playlist at Runtime

Creating a new playlist at runtime with the MediaPlayer class is straightforward. This guide will walk you through the process step-by-step.

Step 1: Define Your Media Items

First, you need to create MediaItem objects that will be part of your playlist. Each MediaItem represents a piece of media that you want to add to your playlist.

Example:

MediaItem song1 = MediaItem.Local("path/to/song1.mp3");
MediaItem song2 = MediaItem.Local("path/to/song2.mp3");
MediaItem song3 = MediaItem.Local("path/to/song3.mp3");

Step 2: Create the Playlist

Once you have your MediaItem objects, you can create a Playlist object and add these items to it.

Example:

Playlist myPlaylist = new Playlist(UriType.StreamingAssets)
{
    MediaItems = new List<MediaItem> { song1, song2, song3 },
    AlbumTitle = "My Favorite Songs"
};

Step 3: Setting the Playlist to the Media Player

If you want to add a new playlist to your existing list of playlists, you can use the AddPlaylist method.

Example:

// Add a new playlist in the end of the current list of playlists
MediaPlayer.AddPlaylist(myPlaylist);

Or you can replace the current playlist with SetPlaylist method.

Example:

// Replace the current playlist with the new playlist
MediaPlayer.SetPlaylist(myPlaylist);

// Replace the playlist at index 2 with the new playlist
MediaPlayer.SetPlaylist(myPlaylist, 2);

Full Example

Here's a complete example of how to create a new playlist and add it to the MediaPlayer:

// Step 1: Define your media items
MediaItem song1 = new MediaItem("path/to/song1.mp3");
MediaItem song2 = new MediaItem("path/to/song2.mp3");
MediaItem song3 = new MediaItem("path/to/song3.mp3");

var mediaItems = new List<MediaItem> { song1, song2, song3 },
string albumTitle = "My Favorite Songs"

// Step 2: Create the playlist
Playlist myPlaylist = new Playlist(mediaItem, albumTitle);

// Step 3: Add the playlist to an already initialized media player
MediaPlayer.AddPlaylist(myPlaylist);

Last updated