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.

1. Determine the Source of Your Media Files

Before creating a playlist, you need to decide where your media files are located. The UriType enum in the MediaPlayer class helps you specify the source of your media files. Here are the available options:

UriType Options

  • StreamingAssets: The media file is located in the StreamingAssets folder.

  • RemoteURL: The media file is located at a remote URL (e.g., http://www.example.com/media.mp3).

    • Android uses 'ExoPlayer' to play the media file.

    • iOS uses 'AVPlayer' to play the media file.

  • DownloadAndPlay: The media file will be downloaded to the 'PersistentDataPath' before playing.

  • PersistentDataPath: The media file is located in the 'PersistentDataPath'.

2. Creating Playlists at Runtime

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 = new MediaItem("path/to/song1.mp3");
MediaItem song2 = new MediaItem("path/to/song2.mp3");
MediaItem song3 = new MediaItem("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");

// Step 2: Create the playlist
Playlist myPlaylist = new Playlist(UriType.StreamingAssets)
{
    MediaItems = new List<MediaItem> { song1, song2, song3 },
    AlbumTitle = "My Favorite Songs"
};

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

Last updated