You can use both the assets
and raw
folder to store audio files which will be compiled with your .APK.
But you should re-consider your strategy in regards to using a filePath
as your parameter. Instead, consider using a string fileName
or an int resource
.
To retrieve a file from the assets
or raw
folder cannot be done using a filePath
in Android. Instead, this is done by either using the AsssetManager
or through a Resource
as mentioned here.
I have also optimised your code a little as the else
clause isn't needed.
Assets folder
When trying to access a file from the assets
folder, you need to use the static method OpenFd
from this.Assets
(where this
is the Context
of your Activity
) with the name of the file. This will return an AssetFileDescriptor
that you can use as a DataSource
as follows:
protected MediaPlayer player;
public void StartPlayer(string fileName)
{
if (player == null)
player = new MediaPlayer();
var fileDescriptor = Assets.OpenFd(filename);
player.Reset();
player.SetDataSource(fileDescriptor.FileDescriptor);
player.Prepare();
player.Start();
}
Raw folder
You can also use the raw
folder which although requires that you point to the auto-generated id
of the given Resource
. This is done using the static Create
method of the MediaPlayer
:
protected MediaPlayer player;
public void StartPlayer(int resource)
{
if (player == null)
player = MediaPlayer.Create(this, resource);
player.Reset();
player.Prepare();
player.Start();
}
Where resource
refers to the audio file in the raw
folder which can be accessed by Resource.raw.youraudiofile
(where youraudiofile
is the name of the audio fie in the raw
folder).
You can read more about using the raw
folder in the Xamarin documentation.