Single Media Item Playlists
In some special scenarios, you might only have one media item to play. Using the SetMediaItem
method can simplify the process of managing your media playback. This method allows you to set a single MediaItem
directly, without the need to create a playlist manually.
Using SetMediaItem
is beneficial when you:
Only need to play one media item.
Want to quickly replace the current media item without managing a full playlist.
Simplify your code for single media item scenarios.
Methods for Setting a Single Media Item
Method 1: Replacing the Current Playlist with a New Media Item
This method allows you to replace the entire playlist with a new media item. It is useful when you want to ensure that only one media item is being played.
Method Signature
public static void SetMediaItem(
MediaItem mediaItem,
int playlistIndex,
bool playWhenReady = false,
int startMediaItemIndex = 0,
float startPosition = 0f);
Parameters:
mediaItem
: TheMediaItem
to set.playlistIndex
: The index of thePlaylist
to set theMediaItem
to.playWhenReady
: Whether to start playback when the plugin is initialized.startMediaItemIndex
: The index of theMediaItem
to start playback from.startPosition
: The position to start playback from.
Example Usage:
MediaItem mediaItem = MediaItem.StreamingAsset("path/to/song.mp3");
MediaPlayer.SetMediaItem(mediaItem, 0, true, 0, 0f);
Method 2: Setting the Current Media Item Directly
This method allows you to set the current media item directly, using the current playlist index. This is a convenient shortcut if you don't need to specify a different playlist index.
Method Signature
public static void SetMediaItem(
MediaItem mediaItem,
bool playWhenReady = false,
int startMediaItemIndex = 0,
float startPosition = 0f);
Parameters:
mediaItem
: TheMediaItem
to set.playWhenReady
: Whether to start playback when the plugin is initialized.startMediaItemIndex
: The index of theMediaItem
to start playback from.startPosition
: The position to start playback from.
Example Usage:
MediaItem mediaItem = MediaItem.StreamingAsset("path/to/song.mp3");
MediaPlayer.SetMediaItem(mediaItem, true, 0, 0f);
Full Example
Here is a complete example demonstrating how to create and play a single media item using both methods:
// Define your media item
MediaItem mediaItem = MediaItem.StreamingAsset("path/to/song.mp3");
// Setting the media item
MediaPlayer.SetMediaItem(mediaItem);
Last updated