Play Audio and Video in .NET MAUI with MediaElement


However as multimedia rich applications become more in demand, developers wish to efficiently incorporate audio and video playback into their apps. Now with .NET MAUI (or .NET Multi-platform App UI with Microsoft), Microsoft delivers an awesome framework for writing cross platform applications with native performance. The new MediaElement control in .NET MAUI is one of the standout features I would say as it makes it super easy to play multimedia content inside your application.

The MediaElement control is a way to play audio and video across multiple platforms, including iOS, Android, macOS and Windows using a single approach. It makes the complexities of playing media irrelevant, and enables developers to concentrate on delivering great user experiences. In this article, we explore how to make use of MediaElement in .NET MAUI apps, including detailed explanations and real life examples.

If you are creating a music player, video player or want to embed multimedia content, you really have to learn to use MediaElement. We should walk you through your development environment setup, playing audio and video, customizing the control and listening to events that should lead to responsive and user friendly applications.

Adding MediaElement To Your MAUI App

To add MediaElement control to your .NET MAUI app you need to add it to your .XAML or you can configure it to play your preferred media files. And both in audio and video playback, we will offer code example and explanation.

Adding Audio Playback

First, add the control to your XAML file and then you can use MediaElement to play audio. You can set the Source of the audio file you are processing. Here’s an example:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             x:Class="MyApp.MainPage">
  <StackLayout>
    <MediaElement x:Name="audioPlayer"
                  Source="https://www.example.com/audiofile.mp3"
                  AutoPlay="False"
                  ShowsPlaybackControls="True" />
    <Button Text="Play Audio" Clicked="OnPlayButtonClicked" />
  </StackLayout>
</ContentPage>

In this example, the MediaElement control is named audioPlayer and the Source is given to an online MP3 file. To keep the page from automatically playing automatically when loaded, we set the AutoPlay property to False. With ShowsPlaybackControls set to true, built in playback controls will show up.

To control playback from code, you can interact with the MediaElement methods in your code-behind:

private void OnPlayButtonClicked(object sender, EventArgs e)
{
    if (audioPlayer.CurrentState == MediaElementState.Playing)
    {
        audioPlayer.Pause();
    }
    else
    {
        audioPlayer.Play();
    }
}

The following code just checks current state of MediaElement and if clicked then toggles between play and pause.

Handling Events
There are a number of events available for the MediaElement control that will notify you of media play, errors and buffering status. For instance, you can subscribe to the MediaEnded event to perform actions when the audio finishes playing:

audioPlayer.MediaEnded += (s, e) =>
{
    DisplayAlert("Playback Completed", "The audio has finished playing.", "OK");
};

This allows you to deal with the events, enabling you to have a responsive user experience by updating the UI, or triggering actions as there’s some state in the media.

Adding Video Playback

This same approach is taken when playing video with MediaElement. You can utilise control to render video content within your application’s UI. Here’s how you can add a video player:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             x:Class="MyApp.VideoPage">
  <Grid>
    <MediaElement x:Name="videoPlayer"
                  Source="https://www.example.com/videofile.mp4"
                  AutoPlay="True"
                  Aspect="AspectFill"
                  ShowsPlaybackControls="True" />
  </Grid>
</ContentPage>

MediaElement has Auto PLay=”True” so that when the video loads, the video will automatically play and the Aspect Property is set to the Aspect Fill that adjusts the video to fit the control bounds.

Handling Events
Handing video playback events is similar to audio playback. For instance, to detect when the video is buffering, you can subscribe to the BufferingProgressChanged event:

videoPlayer.BufferingProgressChanged += (s, e) =>
{
    progressBar.Progress = videoPlayer.BufferingProgress;
};

This code updates a progress bar with buffer status, to show the user the playback status.

Customizing MediaElement

The MediaElement control is very flexible for customization, so you can style and behavior of the MediaElement control to match your application design and user experience needs.

Playback Controls
The ShowsPlaybackControls property defaults standard playback controls. If you want to create custom controls, you can actually set this property to False, and build your own controls to do the playback control.

<MediaElement x:Name="customVideoPlayer"
              Source="video.mp4"
              ShowsPlaybackControls="False" />
<StackLayout Orientation="Horizontal">
  <Button Text="Play" Clicked="OnPlayClicked" />
  <Button Text="Pause" Clicked="OnPauseClicked" />
  <Button Text="Stop" Clicked="OnStopClicked" />
</StackLayout>
private void OnPlayClicked(object sender, EventArgs e)
{
    customVideoPlayer.Play();
}

private void OnPauseClicked(object sender, EventArgs e)
{
    customVideoPlayer.Pause();
}

private void OnStopClicked(object sender, EventArgs e)
{
    customVideoPlayer.Stop();
}

Styling and Layout

The MediaElement control can be styled via XAML styles or by setting properties straight. For example, you can define the width and height to control the video’s display size:

<MediaElement x:Name="styledVideoPlayer"
              WidthRequest="300"
              HeightRequest="200"
              Source="video.mp4" />

Furthermore, you can transform the control, place a border around it or put it into more complex layouts to have the look you want.

Handling MediaElement Events

In order to create responsive applications, you want to learn how to understand and handle MediaElement events. The playback lifecycle is seen through Events such as MediaOpened, MediaEnded, MediaFailed and PositionChanged.

For example, you can handle the MediaFailed event to detect playback errors:

videoPlayer.MediaFailed += (s, e) =>
{
    DisplayAlert("Playback Error", "An error occurred while playing the media.", "OK");
};

By monitoring the PositionChanged event, you can update a slider control to reflect the current playback position:

videoPlayer.PositionChanged += (s, e) =>
{
    positionSlider.Value = videoPlayer.Position.TotalSeconds;
};

These events help to make your application more interactive and allow you to generate feedback or alternative action from the user when things go wrong.

Best Practices

When working with MediaElement, consider the following best practices to ensure optimal performance and user experience:

Resource Management: Since MediaElement is a control, dispose of it properly when it’s no longer needed because leaving the control around will prevent the system resources to be reused. Especially, on mobile devices with limited memory resource.

protected override void OnDisappearing()
{
    base.OnDisappearing();
    videoPlayer.Handler?.DisconnectHandler();
}

Media Formats: Use supported formats media files which will appear in the target platforms. MediaElement works with many common formats, but may be compatible differently on different devices.

Network Connectivity: For streaming your media from online sources, they recommend doing some checks around network availability as well as handling exceptions to prevent crashes and make for a more pleasant user experience.

User Experience: If you have buffering or loading times make sure you give visual cues to keep users aware of the application state such as progress indicators or placeholder images.

Conclusion

In .NET MAUI, the integration of audio and video playback into cross platform applications is simplified with the introduction of the MediaElement control. It allows developers to think of ideas and develop rich multimedia experiences and abstracts away details of multiple implementations.

Here, we provide how to set up and use MediaElement for audio and video playback, style and make changes through Customization of its appearance and controls and how to handle essential events and using best practice. And with that knowledge, you can add engaging media content to your .NET MAUI applications that play nicely on all of the supported platforms.

Once you get more and more into creating Apps with .NET MAUI the MediaElement control will certainly serve you well and give you the ability to build highly interactive and also very flexible Apps that your users will truly appreciate.