Skip to main content

Play Audio and Video in .NET MAUI apps with the new MediaElement

One of the most anticipated controls for .NET MAUI has been released; MediaElement. With MediaElement you can easily play audio and video from within your .NET MAUI app, in this post you’ll learn everything you need to know about this first version and the plans we have for the future!

What is MediaElement?

With MediaElement you gain a powerful control that allows you to play multimedia inside of your .NET MAUI app.

You might already know MediaElement from the Xamarin Community Toolkit where it was added by the amazing work from community member Peter Foot. While that version was already pretty good, it also had room for improvement, especially on Android.

That is why, when porting MediaElement to .NET MAUI, we have rebuilt everything from the ground up. This way we could make sure to keep all the parts that are already good, while improving on the things that could use some love.

Under the hood

For Android we have chosen to use ExoPlayer as the platform counterpart, replacing the Android MediaPlayer that we used for Xamarin. This way we automatically gain a lot of extra features that are available to us out of the box, like playing HTTP Live Streaming (HLS) videos, great looking platform transport controls, and many other things.

On iOS and macOS we’re using the platform AVPlayer as we did for with Xamarin’s MediaElement as well. Also the Tizen one is unchanged using the Tizen.Multimedia.Player.

Now that .NET MAUI builds on top of WinUI instead of UWP, we’re using the WinUI’s brand new MediaPlayerElement here. While this control is also very young to WinUI, it is already very complete and looking promising.

Support for different media formats differ between platforms (and potentially what codecs you have installed), but by using the platform native media players we leverage all the power, and related optimized performance, for each operating system.

Getting started

Getting started with MediaElement is easy. First you want to install the CommunityToolkit.Maui.MediaElement NuGet package. This is a separate package from the main Community Toolkit package.

When the installation completes, go into your MauiProgram.cs and add the following initialization line to the MauiAppBuilder:

public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder
        .UseMauiApp<App>()
        // Initialize the .NET MAUI Community Toolkit MediaElement by adding the below line of code
        .UseMauiCommunityToolkitMediaElement()
        // After initializing the .NET MAUI Community Toolkit, optionally add additional fonts, and other things
        .ConfigureFonts(fonts =>
        {
            fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
        });

    // Continue initializing your .NET MAUI App here

    return builder.Build();
}

Now you’re ready to start using MediaElement in your app! A simple example in XAML can be found below.

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="MediaElementDemos.GettingStarted"
             Title="MediaElement Getting Started">

    <toolkit:MediaElement x:Name="mediaElement"
                      ShouldAutoPlay="True"
                      ShouldShowPlaybackControls="True"
                      Source="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
                      HeightRequest="300"
                      WidthRequest="400"
                      ... />
</ContentPage>

This will add the MediaElement control to a page that starts playing automatically when the video is loaded, the result, running this on iOS and Windows can be seen below.

A screenshot of a .NET MAUI app running on Windows and iOS showing MediaElement

In this blog post I won’t go into too much detail about the rich features that are already in this first version, but one thing is important to point out. You, as the developer, are responsible for releasing the MediaElement resources. For instance an app could play a video in picture-in-picture mode or play audio in the background, with these scenarios it’s impossible to automatically determine when to clean up the MediaElement resources.

Doing so requires just one line of code. In the code snippet below you can see how the resources are freed when the user navigates away from the ContentPage that the MediaElement control is shown on.

public partial class FreeResourcesPage : ContentPage
{
    void ContentPage_Unloaded(object? sender, EventArgs e)
    {
        // Stop and cleanup MediaElement when we navigate away
        mediaElement.Handler?.DisconnectHandler();
    }
}

To learn more about all the current functionalities of MediaElement, check out the documentation page for a deep dive.

I also have made a video where I walk you through some basics on getting started with MediaElement which you can find below.

The future of MediaElement

For this initial released we focused on the core functionality and made sure that that is solid. But from here on out, we can start adding all kinds of amazing features!

One of the requests we hear a lot is support for full-screen video playback. We hear you! However, unfortunately, implementing that is not as straight-forward as it may seem. A discussion is open on the Toolkit repository, feel free to join in!

You can also add your own feature request. I’ve heard many ideas ranging from supporting playlists, being able to play DRM multimedia, subtitle support, and allowing you to set your own custom HTTP headers. Check if your favorite functionality is already in the Discussions tab, if not, open one with as much detail as you can.

We’re looking forward to see your amazing multimedia powered .NET MAUI app projects!

The post Play Audio and Video in .NET MAUI apps with the new MediaElement appeared first on .NET Blog.



source https://devblogs.microsoft.com/dotnet/announcing-dotnet-maui-communitytoolkit-mediaelement/

Comments

Popular posts from this blog

Fake CVR Generator Denmark

What Is Danish CVR The Central Business Register (CVR) is the central register of the state with information on all Danish companies. Since 1999, the Central Business Register has been the authoritative register for current and historical basic data on all registered companies in Denmark. Data comes from the companies' own registrations on Virk Report. There is also information on associations and public authorities in the CVR. As of 2018, CVR also contains information on Greenlandic companies, associations and authorities. In CVR at Virk you can do single lookups, filtered searches, create extracts and subscriptions, and retrieve a wide range of company documents and transcripts. Generate Danish CVR For Test (Fake) Click the button below to generate the valid CVR number for Denmark. You can click multiple times to generate several numbers. These numbers can be used to Test your sofware application that uses CVR, or Testing CVR APIs that Danish Govt provide. Generate

How To Iterate Dictionary Object

Dictionary is a object that can store values in Key-Value pair. its just like a list, the only difference is: List can be iterate using index(0-n) but not the Dictionary . Generally when we try to iterate the dictionary we get below error: " Collection was modified; enumeration operation may not execute. " So How to parse a dictionary and modify its values?? To iterate dictionary we must loop through it's keys or key - value pair. Using keys

How To Append Data to HTML5 localStorage or sessionStorage?

The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time untill unless user deletes his cache, data stored in sessionStorage gets cleared when the originating window or tab get closed. These are new HTML5 objects and provide these methods to deal with it: The following snippet accesses the current domain's local Storage object and adds a data item to it using Storage.setItem() . localStorage.setItem('myFav', 'Taylor Swift'); or you can use the keyname directly as : localStorage.myFav = 'Taylor Swift'; To grab the value set in localStorage or sessionStorage, we can use localStorage.getItem("myFav"); or localStorage.myFav There's no append function for localStorage or sessionStorage objects. It's not hard to write one though.The simplest solution goes here: But we can kee