Click here to Skip to main content
13,148,427 members (67,017 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

9.5K views
3 bookmarked
Posted 25 Mar 2016

Playing audio (mp3) File in Xamarin.Forms

, 25 Mar 2016
Rate this:
Please Sign up or sign in to vote.
Playing audio (mp3) File in Xamarin.Forms

Recently, I had a 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, 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 an Interface which will be implemented in platform specific project, I named it as IAudio.cs and the code for the same is as follows:

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

Now, we need to write the class which will implement this interface in platform specific 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! :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

S Ravi-Kumar-2012
Architect
India India
Hi There, I am an IT professional with 14 years of experience in architecting, designing and building IT solutions for complex business needs in form of mobile & web applications using Microsoft technologies. Currently working in an multinational company in India as Solutions Architect. The articles here are sourced from my blog : http://err2solution.com/

You may also be interested in...

Comments and Discussions

 
PraiseThanks Pin
amnk.info19-Aug-17 19:09
memberamnk.info19-Aug-17 19:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170924.2 | Last Updated 26 Mar 2016
Article Copyright 2016 by S Ravi-Kumar-2012
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid