MAUI — Playing MP3 Files

We will show how easily “raw” MP3 files are played in MAUI with native platform code.

🇺🇦 Bohdan Benetskyi
Nerd For Tech
2 min readJan 3, 2023

--

When it comes to playing sound on mobile devices, there are several ways to do it. You can use a third-party library, such as https://github.com/jfversluis/Plugin.Maui.Audio, or the native methods provided by the operating system(AVFoundation on iOS or MediaPlayer on Android). In this post, we will focus on the native ways to play sound on Android and iOS devices.

Original issue from GitHub: https://github.com/dotnet/maui/discussions/7458#discussioncomment-4499507

Playing sound on Android devices.

On Android, you can use the MediaPlayer class to play sound. The MediaPlayer class can play audio and video files, and it provides a rich set of features such as seeking, looping, and volume control. Here is an example of how to use the MediaPlayer class to play a sound file:

As you can see the MediaPlayer class also provides a set of callback methods that you can override to receive notifications about the status of the media player, such as when the media player has finished playing the sound.

Playing sound on iOS devices.

On iOS, you can use the AVFoundation framework to play sound. The AVFoundation framework provides classes for playing, recording, and editing audio and video. To play a sound on iOS, you can use the AVPlayer class. Here is an example of how to use the AVPlayer class to play a sound file:

Like the MediaPlayer class on Android, the AVAudioPlayer class also provides a set of delegate methods that you can use to receive notifications about the status of the audio player, such as when the audio player has finished playing the sound.

MAUI Shared Code and Configuration.

The last thing is to add an interface for our partial class:

And don’t forget to add special construction to your csproj to build the right files in the right conditions 😅

Location of MP3 files inside MAUI project

Conclusion

In this post, we looked at the native ways to play sound on Android and iOS devices. We saw how to use the MediaPlayer class on Android and the AVPlayer class on iOS to play sound files. Both classes provide a rich set of features and notifications to make playing sound in your mobile app easy.

https://twitter.com/bbenetskyy

--

--