MP3 files in Android for Unity3D
Tags: unity3d, tutorial, csharp
Published: 2022-10-17 22:32:19

Lets say you wanted to build an MP3 player in unity3D so you can listen to YOUR songs with a cool visualizer or maybe while playing a game.

You could drag all the MP3 files into your unity project and simply play the files by changing the clip source of an audio source.

However lets say you wanted to have the ability to add songs from your personal collection (assuming anyone collects MP3's anymore)

It is not as easy as it seems, there is a solution that uses the NAudio API, However I found that it didn't actually work for android, It could read the file and even parse the music data and transcode it to a wav format...however it would not play when building for android and testing on the real device...

This led me to search the unity marketplace which I usually try to avoid as I am usually low on funds and the free assets are usually not all that great, However I do know there are some gems in there, they are far and few between...

That is until I found the Android Native Audio Asset package, this was actually a paid for asset that the developer decided to make free, and I am sure glad he did as it not only solved the problem but solved a really huge problem that I did not even foresee.

That problem being the ability to CONTINUE to play the music while the screen was off or while the app was in the background and best of all, its all done in just a few lines of code...thats right most of all the heavy lifting has been done for us.


So enough about the problem, lets look at the solution.


first it would make sense to actually obtain the asset from the asset store.

[Android Native Audio](https://assetstore.unity.com/packages/tools/audio/android-native-audio-35295)

Add it to your account so you can open the Package Manager and Import it into your project


![Package Manager](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rug208pfnn6cfouof1vp.jpg)

Next we need to call the API from a script.
First lets get a list of all the songs within the android data folder.

```csharp
public FileInfo[] sdcard;
string path = $"{Application.persistentDataPath}";
DirectoryInfo dataDir = new DirectoryInfo(path);
sdcard = dataDir.GetFiles();
```

Basically we create a path that points to the persistantDataPath, next we use the DirectoryInfo class to get information about that folder, including all the files, which we later store into a list of FileInfo, after this the sdcard array has a list of all the files within the folder,

Next you would design some kind of interface for playing the media files, for now we are just going to have it play the first song as a demo.

```csharp
int songID = ANAMusic.load(sdcard[0].Name, true, true, null, true);
ANAMusic.Play(songID);
```

So first we load the first song and store the handle to it as an integer, the next 4 parameters of the load function specify how the music will be loaded and played and how it will react when the application loses focus or the screen turns off.

_ANAMusic.load(string audioFile, bool usePersistentDataPath = false, bool
loadAsync = false, Action<int> loadedCallback = null, bool playInBackground
= false)_

```
Loads a music file into a native Android media player.
audioFile - The path to the music file, relative to Assets\StreamingAssets.
usePersistentDataPath - If true, audioFile is relative to Application.persistentDataPath. If false, it is
relative to Assets\StreamingAssets.
loadAsync - If true, the file is loaded asynchronously and the method immediately returns. If false, the method
will not return until the load has completed.
loadedCallback - If given, the method to call when the load is complete. Must take one int parameter which is
the loaded music ID.
playInBackground - If true, the music will continue playing when the game is not active. If false, the music will
be paused when the game is not active and resumed when it becomes active again.
Returns: int - The ID of the loaded music.
```

Running the application on windows will not let the audio load, however if you build to android and place an mp3 file in the /Android/data/com.myprojectname/files/ running the project will play the mp3 and if you turn the screen off the song keeps playing.

This opens the ability for users to play thier own music during your games or if you just want to build a really cool mp3 player( because those have also disappeared, the latest phones dont even have music players anymore)

Also the asset comes with all the documentation in a nifty PDF format, I hope this helps anyone struggling to play mp3 files from the android file system in Unity.