skip to Main Content

I’m working on a rhythm game in Unity where I store the information needed for a given chart in a JSON file. While information like tempo, name, and an array of notes are fairly straightforward, I’ve been lost when it comes to storing a reference to an MP3 file that contains the audio I want to play alongside a rhythm chart.

With Unity, I’m using a custom class that stores the data that matches the file:

using UnityEngine;

[System.Serializable]
public class MusicChart
{
     public string name;
     public float startDelay;
     public float tempo;
     public float finishBeat;
     public Timing[] timings;
}

Everything here works as intended, I just need something extra to append to the JSON file and this class that will make it work. Apologies for my ignorance, I’m both new to Unity and not well-versed in any complexities JSON might have. I figure the idea of storing the path as a string, then reading that path in on a script in Unity would work, but I don’t know how to do the latter part.

2

Answers


  1. There are a few options:

    1. Store the absolute or relative path to your mp3 file in your json file. This will have the risk that the path is incorrect, is someone copies only the json file, or renames the mp3 file. To do this just add a string musicPath field to your class.
    2. Store the mp3 file inside your json as a base64 encoded string. This will make your json file harder to read, and it will waste some space due to the inefficient encoding.
    3. Store your json and mp3 file inside a zip-archive. Store the entry name of your mp3 file inside your json file. This ensures that the user only sees a single file, but makes it a bit more cumbersome to create or edit files by hand. You can mark the mp3 file as "store" to avoid the compression overhead.

    In all cases you will need to know how read and use the stream representing the mp3 data.

    Login or Signup to reply.
  2. U can convert mp3 file to Base64String and avoiding loosing it :

      var audioBytes = File.ReadAllBytes("PATHTOAudio");
      var base64String = Convert.ToBase64String(audioBytes);
    

    use This method to To play mp3 File :

    static void PlaySoud(string base64String)
        {
            var audioBuffer = Convert.FromBase64String(base64String);
            using (var ms = new MemoryStream(audioBuffer))
            {
                var player = new System.Media.SoundPlayer(ms);
                player.Play();
            }
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search