I'm creating an app for Android, iOS and Windows Phone using Xamarin.forms. My question is how to play a mp3 or wav with Xamarin Forms?
My business logic is handled by Shared Project and I don't know how to use platform specifically "MediaPlayer".
Setup Xamarin Community ToolkitOpen an existing project, or create a new project using the Blank Forms App template. In the Solution Explorer panel, right click on your project name and select Manage NuGet Packages. Search for Xamarin. CommunityToolkit, and choose the desired NuGet Package from the list.
Xamarin. Essentials provides a single cross-platform API that works with any iOS, Android, or UWP application that can be accessed from shared code no matter how the user interface is created. See the platform & feature support guide for more information on supported operating systems.
Right now Xamarin.forms has not sound API, so you need to use DependencyService
Check the following link, it is working fine for me:
https://www.codeproject.com/Articles/1088094/Playing-audio-mp-File-in-Xamarin-Forms
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);
}
}
Android Solution:
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();
}
}
}
iOS Solution:
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();
}
}
}
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With