Categories
.NET MAUI Code Desktop Developer Getting Started Mobile Toolkit Xamarin

.NET MAUI – CommunityToolkit – MediaElement

Most sought after feature of .NET MAUI now available in developer preview to try it out.

The most requested feature from Xamarin.CommunityToolkit package, MediaElement, is now getting ported to the .NET MAUI CommunityToolkit following the MAUI’s very own handler-based implementation.

Peter Foot and other members of the repository are hard at work to make it available by the .NET 7 GA release timeframe scheduled early next month during the .NET Conf 2022.

Now, this has reached a stage where developers can try the preview bits straight from the kitchen (CI feed). Due to the dependencies involved, this is planned as a separate NuGet package titled CommunityToolkit.Maui.MediaElement.

This MediaElement is supported on Android, iOS, MacCatalyst, and Windows. To try the developer preview, a few changes need to be done to add this MediaElement to the .NET MAUI project which is listed below.

Step 1:

Since this is a developer preview, the package is available only through the CI feed, need to configure the feed to access the NuGet package.

Navigate to the root folder of the project and run the following commands

dotnet new nugetconfig
dotnet nuget add source https://pkgs.dev.azure.com/dotnet/CommunityToolkit/_packaging/CommunityToolkit-PullRequests/nuget/v3/index.json -n maui-toolkit

Step 2:

In the case of the .NET 6 targeted project, the Android TFM needs to be updated as it is released on a specific targetSdkVersion. Refer to the screenshot for details. And for projects targeting .NET 7, the android targetSdkVersion is 33 by default, so this step is NOT applicable.

net6.0-android33.0

.NET MAUI CommunityToolkit - MediaElement - Developer Preview - Android TFM update
CommunityToolkit – MediaElement – Android TFM update for .NET 6 Project

Also, update this info in the following file Platforms\Android\AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
	<!-- Other nodes -->
	<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="33" />
</manifest>

Step 3:

Since this MediaElement does depend on some features that are flagged as Preview, it has to be opted-in explicitly. For more info: https://aka.ms/dotnet-warnings/preview-features

<PropertyGroup>
	<!-- Other properties -->
	<EnablePreviewFeatures>True</EnablePreviewFeatures>
</PropertyGroup>

Step 4:

As the MediaElement is built on top of the v1.2.x version (that includes the WinUI 3 MediaPlayerElement control) of the WindowsAppSDK package, update the project file with any one of the following blocks:

<!-- Old approach -->
<ItemGroup Condition="$(TargetFramework.Contains('-windows'))">
	<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.2.221109.1" />
</ItemGroup>
<!-- Generalized approach -->
<ItemGroup Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'windows'">
	<PackageReference Include="Microsoft.WindowsAppSDK" Version="1.2.221109.1" />
</ItemGroup>

Step 5:

Launch the NuGet Package Manager window (option available in the Project context menu – Manage NuGet Packages …), on the top right side of this window, set the Package source to the CI feed of the .NET MAUI CommunityToolkit identified by the name provided in Step 1, maui-toolkit here in this sample). If that particular name is not available in the drop-down even after completing Step 1, close and reopen the solution, then try again.

Step 5a:

From the Browse tab, look for the package named CommunityToolkit.Maui.MediaElement and add the latest CI release of the package to the project.

Step 6:

For the MediaElement handlers to get registered in the .NET MAUI startup pipeline. Call this UseMauiCommunityToolkitMediaElement() method on the MauiAppBuilder object. The changes need to be done in the MauiProgram.cs source file.

public static MauiApp CreateMauiApp()
{
    var builder = MauiApp.CreateBuilder();
    builder.UseMauiApp<App>()
           .UseMauiCommunityToolkitMediaElement()
           .ConfigureFonts(fonts =>
           {
               fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
               fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold");
           });

    return builder.Build();
}

Step 7:

In the XAML page/view of your interest, add the following XML namespace to the root element:

xmlns:media="clr-namespace:CommunityToolkit.Maui.MediaElement;assembly=CommunityToolkit.Maui.MediaElement"

And then make use of the MediaElement view within the content:

Note: In this sample, have set the source to the latest episode of the .NET MAUI Podcast – https://www.dotnetmauipodcast.com/115-2 (Source is one of the bindable properties, which can also be set from the ViewModel property).

<media:MediaElement AutoPlay="True" Source="https://chtbl.com/track/84EGD/aphid.fireside.fm/d/1437767933/306e7564-d5eb-4af3-b3b2-e6aa1f21a9ce/8d384f50-213b-4345-9cbe-3a890db26bdd.mp3" />

MediaElement supports both Audio and Video playback (mp3, mp4) … And Live Streaming with HTTPS (HLS) is also supported.

This has multiple BindableProperties such as AutoPlay, CurrentState, Duration, IsLooping, Position, ShowsPlaybackControls, Source, Speed, VideoHeight, VideoWidth, and Volume.

And exposes the following events to interact with: UpdateStatus, PlayRequested, PauseRequested, StopRequested, MediaEnded, MediaFailed, MediaOpened, and SeekCompleted.

And the following methods to control it: Play(), Pause(), and Stop().

A working sample for both .NET 6 and 7, following all these steps, is now uploaded into my GitHub samples repository. Check out the src/MediaElement folder for the projects.

Happy coding. Stay connected as we continue to learn and share the experiences from this exciting journey of being a .NET developer.

By Vijay Anand E G

A software professional with over a decade long industry experience in developing products that spans across desktop, mobile, and web.

One reply on “.NET MAUI – CommunityToolkit – MediaElement”

Comments are closed.