Search Unity

Question Dynamically loading MP3 Files during runtime.

Discussion in 'Audio & Video' started by mayyorke8, Dec 4, 2023.

  1. mayyorke8

    mayyorke8

    Joined:
    Sep 29, 2022
    Posts:
    3
    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?
     
  2. SeventhString

    SeventhString

    Unity Technologies

    Joined:
    Jan 12, 2023
    Posts:
    416
    You can get an AudioClip from a file on your system using WebRequest:

    Code (CSharp):
    1. public void PlayFile(string fileName)
    2. {
    3.     string path = Path.Combine(Application.persistentDataPath, fileName);
    4.     string uri = "file://" + path;
    5.  
    6.     StartCoroutine(LoadAndPlay(uri));
    7. }
    8.  
    9. IEnumerator LoadAndPlay(string uri)
    10. {
    11.     using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(uri, AudioType.MPEG))
    12.     {
    13.         yield return www.SendWebRequest();
    14.  
    15.         if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
    16.         {
    17.             Debug.LogError("Error: " + www.error);
    18.         }
    19.         else
    20.         {
    21.             AudioClip clip = DownloadHandlerAudioClip.GetContent(www);
    22.             audioSource.clip = clip;
    23.             audioSource.Play();
    24.         }
    25.     }
    26. }