Playing Audio with the MediaManager Plugin for Xamarin.Forms!

Let me show you how to play Audio in Xamarin.Forms across Android, iOS and Windows UWP using the super easy plug and play MediaManager Plugin.

So you wanna play Audio in your Xamarin.Forms app? Stream an audio file over the internet or stored locally in your device Gallery? Listening to songs or podcasts even when the app is in background mode or device is locked away? Then you’re in the right place! 😉

So playing audio in a music player style sounds like a complete nightmare for a cross-platform framework like Xamarin.Forms, but thanks to this incredible MediaManager plugin, just a breeze of work to deploy across Android, iOS and Windows UWP environments.

MediaManager Plugin!

Long time back I remember reading up the article in Xamarin Blog, Play Audio and Video with the MediaManager Plugin for Xamarin, https://devblogs.microsoft.com/xamarin/play-audio-and-video-with-the-mediamanager-plugin-for-xamarin/

Back then, I remember there were no direct support for Xamarin.Forms itself, but now we do, with simple plug and play capabilities in this MediaManager Plugin!

Github:
github.com/Baseflow/XamarinMediaManager
Nuget:
nuget.org/packages/Plugin.MediaManager/

Please feel free to take a look at their official github page, and the implementation code if you’re interested in digging down deep.

Backstory…

I was lucky enough to stumble upon the opportunity to explore the implementation of Audio playback in one of the Xamarin.Forms project I’m working on recently. The core feature of that app was to play audio sources that are stored online, with continuous app background playback enabled, similar to a music player or podcast player.

The first thing came to my mind was the MediaManager plugin. So I tried it out following the Github page and the Xamarin blog article.

But unfortunately I came across a lot of issues, trying to set up in a fresh Xamarin.Forms project itself, even though I followed the steps to the detail. So I had to scrape through old forums and sample projects off of Github, for a series of trial and error, figuring out the proper set up.

It turns out all the articles and documented setup guidelines are mostly outdated, and the Plugin has gone through so much new changes and improvements over the years. So I thought of sharing my experience on setting up the MediaManager Plugin for Xamarin.Forms, step by step from scratch! 😉

Sneak Peek!

Let me share a little sneak peek into the cute little demo I built…

That’s the beauty with a whole bunch of awesome features powered by MediaManager Plugin!

I’ve published this whole awesome demo up in my github repo,

Github repo:
github.com/UdaraAlwis/XFAudioPlayer

Feel free to take a look for a headstart before we begin! 😉

Setting it up!

Let’s begin with the set up of the Plugin with your Xamarin.Forms project. So I’m going to be using a fresh out of the box Xamarin.Forms project with the version 1.5.3.2, which is the latest updated version as of now.

Open up the Nuget Package Manager, on the Solution node, and search for Plugin.MediaManager.Forms package, and make sure to install it on your .NET Standard project node only, as shown below.

As of the writing of the blog post, I would recommend sticking to v6.94 version of the plugin as you can see above. The latest version had given me some run time issues.

It is important that you install the plugin only in the .NET Standard project, hence we’re using the Xamarin.Forms related package of the MediaManager plugin.

Also you may have noticed, there are multiple other packages related to MediaManager plugin, which caters for different purposes such as Plugin.MediaManager for Xamarin Native, Plugin.MediaManager.Reactive for Reactive Extensions, Plugin.MediaManager.ExoPlayer for ExoPlayer based implementations and so on.

Feel free to play around with them if you ever come across the need for such. Next we need to configure the initiation of the plugin.

No initiation setup required in platform projects, but in the App.xaml.cs of your Xamarin.Forms project node,

public partial class App : Application
{
	public App()
	{
		InitializeComponent();

		CrossMediaManager.Current.Init();

		MainPage = new NavigationPage(new MainPage());
	}
}

Oki doki, you’re good go!

Let the coding begin!

It’s actually easy to use Plugin.MediaManager in Xamarin.Forms! It provides a Singleton access to the complete player plugin instance, CrossMediaManager.Current, so you get full control of all the properties, behaviours and features in one place across the entire app context.

First, Play Audio!

Just hit the Play() for your audio as simple as below…

var audioUrl = "https://ia800605.us.archive.org/32/items/Mp3Playlist_555/Daughtry-Homeacoustic.mp3";
await CrossMediaManager.Current.Play(audioUrl);

Yes! it’s that simple. Check here the full list of Play() method overrides available: https://github.com/Baseflow/XamarinMediaManager#other-play-possibilities

Player Features!

Any Audio player should have the basic features such as Auto Play, Shuffle, Repeat mode and so on yeah? 😉

CrossMediaManager.Current.ShuffleMode = ShuffleMode.All;
CrossMediaManager.Current.PlayNextOnFailed = true;
CrossMediaManager.Current.RepeatMode = RepeatMode.All;
CrossMediaManager.Current.AutoPlay = true;

CrossMediaManager.Current instance provides you direct access to all those features you need.

Play, Pause, Stop, Resume?!?

Yeah well those key features of are easily accessible, and then some! 😉

var result = await CrossMediaManager.Current.Play();
var result = await CrossMediaManager.Current.Pause();
var result = await CrossMediaManager.Current.Stop();

All those returns a bool indicating the results of the action.

var result = await CrossMediaManager.Current.PlayPrevious();
var result = await CrossMediaManager.Current.PlayNext();

How about if it’s playing, then pause, it its pause, then resume play?

await CrossMediaManager.Current.PlayPause(); 

Yeah it’s got a feature for that too! 😀 which I’ve also used in my demo.

Step and Seek!

Yep, not hide and seek for sure…

// step forward or backwards
await CrossMediaManager.Current.StepForward();
await CrossMediaManager.Current.StepBackward();  

// seek to a specific position          
await CrossMediaManager.Current.SeekTo(timespan);

You can even adjust the default value for stepping actions using, CrossMediaManager.Current.StepSize and then directly seek to a specific location of the audio using SeekTo with a TimeSpan value! 😉

Access Media data…

You can load the metadata or media details of the audio source as follows,

IMediaItem currentMediaItem = await 
         CrossMediaManager.Current.Play(audioUrl);

Whenever you call Play() method it will return IMediaItem object which contains all the metadata regarding the audio source, such as Title, Artist, Album, Year, and etc…

Sometimes the retrieval of the metadata could take a while depending on the media source or the run time platform, so you can subscribe to the MetadataUpdated event to retrieve the data once they’re extracted.

var mediaItem = await CrossMediaManager.Current.Play(audioUrl);
mediaItem.MetadataUpdated += (sender, args) => {
	var title = args.MediaItem.Title;
};

This might be a bit troublesome, subscribing and unsubscribing, so you could access the metadata from the Queue instance directly, CrossMediaManager.Current.Queue.Current

IMediaItem currentAudioItem
       = CrossMediaManager.Current.Queue.Current;

Or directly as follows..

var title = CrossMediaManager.Current.Queue.Current.Title;
var artist = CrossMediaManager.Current.Queue.Current.Artist;
var album = CrossMediaManager.Current.Queue.Current.Album;
...

You can bind your UI properties to these values, once you execute Play() on your audio.

Now that I mentioned Queue, let’s get into that next…

Queue it up!

MediaManager simplifies a whole bunch features for you, and one of them is the Queue, which you can access directly through the instance, CrossMediaManager.Current.Queue which provides the IMediaQueue object. This one carries a whole bunch of awesomeness that you can use for your own player.

var currentMediaItem 
          = CrossMediaManager.Current.Queue.Current;
var nextMediaItem 
          = CrossMediaManager.Current.Queue.Next;
var previousMediaItem 
          = CrossMediaManager.Current.Queue.Previous;

In my demo I’m using the the override of passing a List of media urls to be played in a queue,

var songList = new List<string>() {
	"https://files.freemusicarchive.org/storage-freemusicarchive-org/music/no_curator/Yung_Kartz/July_2019/Yung_Kartz_-_02_-_Levels.mp3",
	"https://files.freemusicarchive.org/storage-freemusicarchive-org/music/Creative_Commons/Ketsa/Raising_Frequency/Ketsa_-_08_-_Multiverse.mp3",
	...
};

var currentMediaItem = 
	await CrossMediaManager.Current.Play(songList);

I could easily access it using the CrossMediaManager.Current.Queue.MediaItems

ObservableCollection<IMediaItem> mediaItemsInQueue 
	= CrossMediaManager.Current.Queue.MediaItems;

It returns an ObservableCollection of the MediaItems that I have queued up.

var mediaItem =
	CrossMediaManager.Current.Queue[index];

Just like that you could retrieve a specific item from the Queue as well.

Add to Queue…

To add an item directly to the Queue using the Queue.Add() method but, you need MediaItem object of that audio source. You can use the MediaExtractor object to create the MediaItem object you require and add that to the Queue as follows…

var generatedMediaItem =
	await CrossMediaManager.Current
	.Extractor.CreateMediaItem(mediaUrl);
	
CrossMediaManager.Current.Queue.Add(generatedMediaItem);

Now that new audio source will be added to the bottom of the Queue waiting to be played..

Play from Queue…

Use PlayQueueItem() to play an item from the Queue…

// from index
var isSuccess = 
     await CrossMediaManager.Current.PlayQueueItem(index);

// pass in the MediaItem
var isSuccess = 
      await CrossMediaManager.Current.PlayQueueItem(mediaItem);

Or better yet, pass in the MediaItem itself from the queue, it will return a bool whether it was found in the queue and started playing or not.

Player State matters!

You might say, Play this, Play that, but how do you know if it’s actually playing or not? even before that is it still loading the media source? or still buffering the data?

You can easily monitor this by subscribing to StateChanged event,

CrossMediaManager.Current.StateChanged += Current_OnStateChanged;
...

private void Current_OnStateChanged(object sender, StateChangedEventArgs e)
{
	if (e.State == MediaPlayerState.Playing)
	{
		// playing mode
	}
}

MediaPlayerState enum provides us 6 states of the media playback,

  • Loading
  • Buffering
  • Failed
  • Playing
  • Paused
  • Stopped

You could also check the state suing extension methods,

var result = CrossMediaManager.Current.IsPlaying();
var result = CrossMediaManager.Current.IsBuffering();
var result = CrossMediaManager.Current.IsStopped();

These nifty little extensions returns a boolean value with regards to the state.

Better yet you also got a singleton property you can bind to,

MediaPlayerState state = CrossMediaManager.Current.State;
if (state == MediaPlayerState.Playing)
{
	// playing mode
}

Yep multiple flexible ways! 😉 There’s another useful extension method, CrossMediaManager.Current.IsPrepared() which allows you check if the Player is already set up with Audio sources, and is running.

In my demo app I use this in the home page where I need to make sure the Player instance is already initialised or not with audio sources every time I activate the app from background.

protected override async void OnAppearing()
{
	base.OnAppearing();

	if (!CrossMediaManager.Current.IsPrepared())
	{
		await InitPlay();
	}
}

Pretty handy!

Useful Events…

There are plenty useful events you can subscribe to in order to monitor different properties and behaviors, https://github.com/Baseflow/XamarinMediaManager#hook-into-events

CrossMediaManager.Current.StateChanged
	+= Current_OnStateChanged;
CrossMediaManager.Current.PositionChanged
	+= Current_PositionChanged;
CrossMediaManager.Current.MediaItemChanged
	+= Current_MediaItemChanged;

I for one am subscribing to these events in my demo app, for monitoring Player State changes, current Media playback Position changes, current MediaItem Change. These events provides specific types of EventArgs parameters which you can use in the event methods.

Keep track of Time!

It’s important to keep track of the playback time data such as, Position and Duration of the audio that you’re playing. In my demo I use the PositionChanged event and Position, Duration properties to update the UI accordingly to show the user playback time data.

TimeSpan currentMediaPosition
	= CrossMediaManager.Current.Position;
TimeSpan currentMediaDuration
	= CrossMediaManager.Current.Duration;

Here’s how I update some of the UI elements based on the Position and Duration changes..

var formattingPattern = @"hh\:mm\:ss";
if (CrossMediaManager.Current.Duration.Hours <= 0)
	formattingPattern = @"mm\:ss";

var fullLengthString =
	CrossMediaManager.Current.Duration.ToString(formattingPattern);
LabelPositionStatus.Text =
	$"{CrossMediaManager.Current.Position.ToString(formattingPattern)}/{fullLengthString}";

SliderSongPlayDisplay.Value =
	CrossMediaManager.Current.Position.Ticks;

All kinds of cool UI bits you could implement with those data! 😀

Loading Local Audio files..

Now this is a cool little feature I decided to implement. My demo app will be able to load local Audio files from the local file system, into the app, and play! 😉

This should work seamlessly across Android, iOS and UWP. So I’m going to be using another nifty little library called, FilePicker-Plugin-for-Xamarin-and-Windows, which will simplify the whole file picking set up much easier.

I need to allow only MP3 audio file types to be picked in the app, so let’s define that first,

string[] fileTypes = null;
if (Device.RuntimePlatform == Device.Android)
{
	fileTypes = new string[] { "audio/mpeg" };
}

if (Device.RuntimePlatform == Device.iOS)
{
	fileTypes = new string[] { "public.audio" };
}

if (Device.RuntimePlatform == Device.UWP)
{
	fileTypes = new string[] { ".mp3" };
}

So based on the platform we need to set appropriate filter values before we execute picking. Next let’s pick the file using our FilePicker library and load into our media queue…

var pickedFile = await CrossFilePicker.Current.PickFile(fileTypes);
if (pickedFile != null)
{
	var cachedFilePathName = Path.Combine(FileSystem.CacheDirectory, pickedFile.FileName);

	if (!File.Exists(cachedFilePathName))
		File.WriteAllBytes(cachedFilePathName, pickedFile.DataArray);

	if (File.Exists(cachedFilePathName))
	{
		// Create media item from file
		var generatedMediaItem =
			await CrossMediaManager.Current
			.Extractor.CreateMediaItem(cachedFilePathName);
		// Add media item to queue
		CrossMediaManager.Current.Queue.Add(generatedMediaItem);
	}
}

Once the user picks the file, we get the FileData object. I’m writing that file object to the app cache directory with the help of Xamarin.Essentials.FileSystem helpers.

It is better to load the file into memory from the cache directory hence some platforms could flag directly accessing files outside the app directories as a suspicious activity and eventually break the flow of the app.

Once we store the file safely in App Cache directory, we load it into our app, using the Extractor to create the IMediaItem object and pass it on to the MediaManager’s queue. 😉

Well that’s all the tidbits I got to share regarding the little demo I built!

Demo time!

So I built a simple demo audio player which will be playing MP3 audio sources stored online, and as an extra functionality, it will allow us to play locally stored MP3 files as well.

Github repo:
github.com/UdaraAlwis/XFAudioPlayer

The first page, which is the Home page, will host the main Audio Play feature, such as Play/Pause, Next, Previous and so on. Then another page which will display the current audio Queue loaded into the Player. The same page will have the functionality to load local MP3 files and add to the Queue on the go…

Let’s fire it up and see the magic! 😉

Here we got iOS working like a charm! Well I’m not able to showcase the background or lock screen activity since I’m running it on the iOS Simulator and I don’t have an actual iPhone 😛

Next we got Android, working marvelously… 😉 Here I’m showcasing the full length of features including continuous playback on app background state as well!

Here’s the good old UWP Windows, working like a breeze! App will continue playing even if the app is minimized or device is locked as expected for background playback state! 😀

Remember I told yol about the extra little feature I added, being able to load local Audio files!? here we have it, working like a charm across iOS, Android and UWP Windows…

Let me flex a little bit more on the continuous background audio playback… 😉

As you can see on Android, we got direct access to media playback while the app is on background mode, and the audio is still playing even on lock screen…

Then on UWP Windows runtime we got the same exact features, it even complies with device native media buttons on the laptop keyboard!

Oh also on Windows 10 lock screen at the bottom right corner… 😉

Woot! Woot! 😀

Issues…

Even though I managed to build this cool little demo, with the help of MediaManager Plugin, I did notice some issues with it.

On UWP Windows runtime, it wasn’t loading Audio meta data for sources which are stored online. As in for any internet audio source, it would not be able to load the meta data of it. I saw some issues raised in the github page regarding this. So for now, just during UWP run time, we should rely on manually loading the audio source metadata, hopefully until the issue is fixed. Although my guess is, it could be a Windows File system security restriction!?

Another issue is that on Android, if the app is killed manually while its in background, the audio playback will stop it self. Usually this shouldn’t happen as far as I’ve seen with other Audio player apps. There’s a pending issue logged in github for this as well.

Well that was pretty much it for the issues I noticed!

Conclusion

Well it was certainly fun little walk down the memory lane, apart from the trouble I had to go through following out of sync documentation. lol but it was worth it. It’s incredible how far MediaManager Plugin has come so far since the early days of Xamarin, and kudos to the developer @martijn00

MediaManager Plugin takes away all the pain of dealing with platform native handling of audio files and provide us direct access to great audio features. If you ever come across implementing an audio player app, this would be a great plugin to consider. Hope this little documentation of my experience with it was helpful for anyone out there! 🙂

Share the love! 😀 Cheers yol!

5 thoughts on “Playing Audio with the MediaManager Plugin for Xamarin.Forms!

  1. I have some issues using this plugin (Xamarin Forms, Android app only):

    1. If the lock screen appears (or I change of app) and I tap the notification bar (the controls work fine) to get the app again, all pages in my Navigation stack are closed. The music or audio (if I play a video) still sounds for a while.

    2. The player controls doesn’t have a “full screen” button. I can’t use a modal page to show the player because it closes if the user changes between apps. I would like this feature to view the video player horizontally automatically, exactly as YouTube does.

    Like

  2. Thanks a lot for sharing appreciate it. I have one question is like the bool IsPlaying, IsBuffering are not working anymore. I try display activity indicator using these booleans but it’s not working

    Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.