Перейти к основному содержимому

MediaPlayer

The MediaPlayer class provides the core functionality for media playback in Avalonia applications. It handles media loading, playback control, and platform-specific backend management, serving as the engine behind the MediaPlayerControl.

Properties

Media Source Properties

PropertyTypeDescription
SourceMediaSourceGets or sets the media source to be played (UriSource or StreamSource).

Playback Properties

PropertyTypeDescription
PositionTimeSpanGets or sets the current playback position.
DurationTimeSpan?Gets the total duration of the media. Null for non-seekable media.
LoadedBehaviorMediaPlayerLoadedBehaviorGets or sets playback behavior when media is loaded.

State Properties

PropertyTypeDescription
IsSeekableboolGets whether the current media supports seeking.
IsBufferingboolGets whether the media is currently buffering.
BufferProgressdouble?Gets buffer progress (0.0-1.0). Null if not available.
HasVideoboolGets whether the current media contains video content.
LastErrorMessagestringGets the most recent error message in error state.

Audio Properties

PropertyTypeDescription
VolumedoubleGets or sets the playback volume (0.0-1.0).
IsMutedboolGets or sets whether audio is muted.

Advanced Properties

PropertyTypeDescription
StatisticsMediaStatisticsGets playback statistics information if available.
ForceVlcBackendbool (static)Forces the use of VLC backend (debugging only).

Events

EventDescription
NaturalSizeChangedOccurs when the natural size of the video changes.
MediaPreparedOccurs when the media has been prepared and is ready.
MediaStartedOccurs when media playback has started.
MediaPausedOccurs when media playback has been paused.
MediaStoppedOccurs when media playback has been stopped.
MediaPlaybackCompletedOccurs when media playback has completed.
ErrorOccurredOccurs when an error is encountered.
PropertyChangedStandard INotifyPropertyChanged event.

Methods

MethodReturn TypeDescription
InitializeAsync()TaskInitializes the media player and its backend.
PrepareAsync()TaskPrepares the media for playback.
PlayAsync()TaskStarts or resumes media playback.
PauseAsync()TaskPauses media playback.
StopAsync()TaskStops media playback.
ReleaseAsync()TaskReleases resources for the current media.
UnInitialize()TaskReleases all resources used by the player.

Backend Architecture

The MediaPlayer uses a pluggable backend architecture to support different platforms:

The backend selection is automatic based on the platform:

graph TD
MP[MediaPlayer] --> IMPB[IMediaPlayerBackend]
IMPB --> AVFB["AVFoundation<br/>(macOS/iOS)"]
IMPB --> EPB["ExoPlayer<br/>(Android)"]
IMPB --> VLCB["LibVLC<br/>(Linux)"]
IMPB --> MFB["Media Foundation<br/>(Windows)"]
MP:::main
IMPB:::interface
MFB:::impl
AVFB:::impl
EPB:::impl
VLCB:::impl

Usage Examples

Basic Playback

// Create and initialize
var player = new MediaPlayer();
await player.InitializeAsync();

// Configure
player.Volume = 0.8;
player.LoadedBehavior = MediaPlayerLoadedBehavior.Manual;

// Load and play media
player.Source = new UriSource("https://example.com/audio.mp3");
await player.PrepareAsync();
await player.PlayAsync();

Event Handling

// Setup event handlers
player.MediaPrepared += (s, e) => Console.WriteLine("Ready to play");
player.MediaStarted += (s, e) => Console.WriteLine("Playback started");
player.MediaPlaybackCompleted += (s, e) => Console.WriteLine("Playback completed");

// Error handling
player.ErrorOccurred += (s, e) => {
Console.WriteLine($"Error: {e.ErrorMessage}");
};

Resource Cleanup

// Clean up when done
await player.StopAsync();
await player.ReleaseAsync();
await player.UnInitialize();

Error Handling

The MediaPlayer uses an event-based approach to error handling:

  • When an error occurs, the player transitions to an Error state internally
  • The ErrorOccurred event is raised with detailed error information
  • Most methods check for the Error state and will not proceed
  • Call ReleaseAsync() to reset the error state
// Subscribe to error events
player.ErrorOccurred += (sender, args) =>
{
// Handle the error appropriately here with your custom logic.
// Reset with ReleaseAsync() elsewhere if you need to playback again.
// ...
Console.WriteLine($"Error: {args.Message}");
};

// Try to play media
try {
await player.PlayAsync();
}
catch (Exception ex) {
// Fallback exception handling if needed
if (player.LastErrorMessage != null) {
Console.WriteLine($"Error: {player.LastErrorMessage}");

// Optionally reset the player
await player.ReleaseAsync();
}
}

Best Practices

  1. Initialization and Cleanup:

    • Always call InitializeAsync() before using MediaPlayer.
    • Call ReleaseAsync() between loading different media sources.
    • Call UnInitialize() when completely done with MediaPlayer.
  2. Error Handling:

    • Subscribe to the ErrorOccurred event to handle playback errors.
  3. Resource Management:

    • Properly clean up to avoid resource leaks.
    • Consider reusing a single MediaPlayer instance for multiple media items that are to be played sequentially.
  4. Platform Considerations:

    • Test media playback on all target platforms.