Playing audio (mp3) File in Xamarin.Forms

Playing audio (mp3) File in Xamarin.Forms

Recently I had requirement to play mp3 file in one of my Xamarin Forms application, when I searched over the internet I came to know that currently Xamarin Forms doesn’t support playing audio files out the box. But as every Xamarin Forms developer knows that we can achieve any native functionality using dependency service so I thought why not give this a try 🙂 So here it goes.

We would require to create a Interface which will be implemented in platform specific project, I named it as IAudio.cs and the code fore same is as follows

using System;
namespace AudioPlayEx
{
	public interface IAudio
	{
		void PlayAudioFile(string fileName);
	}
}

Now we need to write the class which will impliment this interface in platform specfic code . I named the class as ‘AudioService’ in both platforms

The android project class will be like this :

using System;
using Xamarin.Forms;
using AudioPlayEx.Droid;
using Android.Media;
using Android.Content.Res;

[assembly: Dependency(typeof(AudioService))]
namespace AudioPlayEx.Droid
{
	public class AudioService: IAudio
	{
		public AudioService ()
		{
		}

		public void PlayAudioFile(string fileName){
			var player = new MediaPlayer();
			var fd = global::Android.App.Application.Context.Assets.OpenFd(fileName);
			player.Prepared += (s, e) =>
			{
				player.Start();
			};
			player.SetDataSource(fd.FileDescriptor,fd.StartOffset,fd.Length);
			player.Prepare();
		}
	}
}

Make sure that the audio files you are planning to play are copied in ‘Assets’ folder then only the above code will work.

And the iOS project class will be like this :


using System;
using Xamarin.Forms;
using AudioPlayEx;
using AudioPlayEx.iOS;
using System.IO;
using Foundation;
using AVFoundation;

[assembly: Dependency (typeof (AudioService))]
namespace AudioPlayEx.iOS
{
	public class AudioService : IAudio
	{
		public AudioService ()
		{
		}

		public void PlayAudioFile(string fileName)
		{
			string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), Path.GetExtension(fileName));
			var url = NSUrl.FromString (sFilePath);
			var _player = AVAudioPlayer.FromUrl(url);
			_player.FinishedPlaying += (object sender, AVStatusEventArgs e) => {
				_player = null;
			};
			_player.Play();
		}
	}
}
 

In case of iOS project you will need to copy the audio files to ‘Resources’ folder.

And finally we will use the following code in our PCL/shared project in order to play the audio file


	DependencyService.Get<IAudio>().PlayAudioFile("MySong.mp3");

You can call this code in the click of a button event or any other event in your PCL/Shared project. In the above example I have played an mp3 file but you can use the same code to play any audio file supported by the platform for example .aif (only in iOS), mp4, wav etc.

You can get the example source code from here Happy Coding 🙂

 

14 thoughts on “Playing audio (mp3) File in Xamarin.Forms

  1. This is really great and very much appreciated!
    Question: How can you specify a file elsewhere on the tablet, besides the Assets or Resources folder? For example, if your app downloads a file to a directory you’ve created. You know the directory and the name, but its not part of the App assets.

    1. If you know the path and how to access that path in platform specific code then you can change/update the implementation of Play method in platform specific projects to get file from that location.

  2. Thanks for providing a workable solution for a specific question that has been the subject of misinformation from the blogs, could not scope to non-existent documentation that is pertinent, within a sea of latest versions for Media Player.

  3. Very good article, however it appears that as soon as AVAudioPlayer starts playing, it somehow goes out of scope and abruptly stops. I was wondering how best to combat this?

    In my XF Page I declare an instance of IAudio at class level and then in my constructor I set it and begin playing however no luck. Any advice would be much appreciated

    1. Hi Adam, Sorry I was stuck in some other tasks so was not able to reply to your comment, however I saw at github that you have fixed the issue and submitted a pull request. Thanks for the same, I have accepted the PR and merged it to the repo. –Regards S Ravi Kumar

  4. Here is the code for UWP:

    using System;
    using Xamarin.Forms;
    using AudioPlayEx;
    using AudioPlayEx.UWP;
    using Windows.Storage;
    using Windows.UI.Xaml.Controls;

    [assembly: Dependency(typeof(AudioService))]
    namespace AudioPlayEx.UWP
    {
    public class AudioService : IAudio
    {
    public MediaElement PlayMusic;

    public AudioService ()
    {
    }

    public async void PlayAudioFile(string fileName)
    {
    PlayMusic = new MediaElement();
    StorageFolder Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
    Folder = await Folder.GetFolderAsync(“Assets”);
    StorageFile sf = await Folder.GetFileAsync(fileName);
    PlayMusic.SetSource(await sf.OpenAsync(FileAccessMode.Read), sf.ContentType);
    PlayMusic.Play();
    }
    }
    }

      1. Thank you for a great example on playing an audio file in Xamarin srkrathore. Hope my sample helps those that would like to add UWP to their Xamarin project. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *