Hello,
I am experimenting with making a rhythm game in unity. I want to make it so you can drag any mp3 file into Applications.persistantdatapath, or really any fixed non-changing directory would work, and then the player would type in a file name - for example " Test.mp3" - and it would read/load the file at that path with that name, and play it through an audio source. This would allow for me to pre package the game with 5-10 songs, while letting players add their own quickly and simply. for the life of me I cannot figure out how to read an MP3 file from there.
Does anybody know how to do this?
You can get an AudioClip from a file on your system using WebRequest:
public void PlayFile(string fileName)
{
string path = Path.Combine(Application.persistentDataPath, fileName);
string uri = "file://" + path;
StartCoroutine(LoadAndPlay(uri));
}
IEnumerator LoadAndPlay(string uri)
{
using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(uri, AudioType.MPEG))
{
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError("Error: " + www.error);
}
else
{
AudioClip clip = DownloadHandlerAudioClip.GetContent(www);
audioSource.clip = clip;
audioSource.Play();
}
}
}