MediaPlayer Quick Start Guide
This guide provides a practical introduction to implementing media playback in Avalonia applications using the Avalonia
Accelerate MediaPlayer package.
Installation
See the Installation Guide for step-by-step instructions on how to install Accelerate components.
Add the MediaPlayer package to your project:
dotnet add package Avalonia.Controls.MediaPlayer
Add the default theme to your App.axaml:
<Application.Styles>
<FluentTheme/>
<!-- Add this declaration for the default theme. -->
<MediaFluentTheme/>
</Application.Styles>
Add the License Key
Include your Avalonia UI license key in the executable project file (.csproj):
<ItemGroup>
<AvaloniaUILicenseKey Include="YOUR_LICENSE_KEY" />
</ItemGroup>
For multi-project solutions, you can store your license key in an environment variable or a shared props file to avoid duplication.
Basic Usage
Using MediaPlayerControl (Recommended)
The easiest way to add media playback to your Avalonia app is using the MediaPlayerControl, which provides a full-featured UI by default:
<Window xmlns="https://github.com/avaloniaui"
Width="800" Height="450">
<MediaPlayerControl Name="mediaPlayer"
Source="{Binding MediaSource}"
Volume="0.8"/>
</Window>
Using MediaPlayer Directly
For more control, you can use the MediaPlayer class directly:
// Create and initialize a MediaPlayer
var player = new MediaPlayer();
await player.InitializeAsync();
// Set properties
player.Volume = 0.8;
player.LoadedBehavior = MediaPlayerState.AutoPlay;
// Load and play media
player.Source = new UriSource("https://example.com/audio.mp3");
await player.PrepareAsync();
await player.PlayAsync();
Loading Media Sources
From Files or URLs using UriSource
// Local file
mediaPlayer.Source = new UriSource("file:///C:/videos/sample.mp4");
// or
mediaPlayer.Source = new UriSource(new Uri("file:///C:/videos/sample.mp4"));
// Remote URL
mediaPlayer.Source = new UriSource("https://example.com/video.mp4");
Note: If it's possible, always add the file:// schema to your local file URI's. This makes sure that
the player recognizes the file's path as local.
From Streams with StreamSource
// From file stream
var fileStream = File.OpenRead("path/to/video.mp4");
mediaPlayer.Source = new StreamSource(fileStream);
// From memory stream
var memoryStream = new MemoryStream(byteArray);
mediaPlayer.Source = new StreamSource(memoryStream);
Note: Make sure to not control the disposal of the stream you passed to the StreamSource as the player will take
care of its lifetime.
Using File Picker with StorageFileSource
public async void OpenFile_Click(object sender, RoutedEventArgs e)
{
var storageProvider = TopLevel.GetTopLevel(this)?.StorageProvider;
if (storageProvider == null) return;
var files = await storageProvider.OpenFilePickerAsync(new FilePickerOpenOptions
{
AllowMultiple = false
});
if (files.Count != 1) return;
if (files[0].Path is not { } path) return;
mediaPlayer.Source = new StorageFileSource(files[0]);
}