How to play audio on Android using Xamarin Forms? I have the following service, this works but Forms.Context
is deprecated with the message "Context is obsolete as of version 2.5. Please use a local context instead.".
[assembly: Dependency(typeof(AudioService))]
namespace SensaLabScan.Droid.Services
{
public class AudioService : IAudioService
{
private readonly MediaPlayer _mediaPlayer = new MediaPlayer();
public void PlayBeep()
{
_mediaPlayer.Reset();
// Forms.Context references the Activity which calls Forms.Init, i.e. MainActivity.
using (var beepFile = Forms.Context.Assets.OpenFd("beep.mp3"))
{
_mediaPlayer.SetDataSource(beepFile);
_mediaPlayer.Prepare();
_mediaPlayer.Start();
}
}
}
}
What is the alternative to the deprecated Forms.Context
in this scenario? I've tried
Android.App.Application.Context.Assets.OpenFd("beep.pm3");
but this raises a file not found exception- Using the
MainActivity
as the context and using theAssets
from that, but again a file not found error.
The mp3 files I'm looking to read are in the Assets folder and marked as AndroidAsset.