N
N
NeoLight32020-08-10 21:23:34
C++ / C#
NeoLight3, 2020-08-10 21:23:34

How to play MP3/OGG ​​file from bytes in Unity game?

I read various English forums on this issue:
https://answers.unity.com/questions/686240/audiocl...
https://stackoverflow.com/questions/16078254/creat...

However, some of them were either related with loading via HTTP, or a non-working method.
Here is my code:

public void makeSound(CommandArgs args)
        {
      try
      {
        var bytes_music = File.ReadAllBytes("Unturned_Data/Managed/mods/clip.ogg");
        float[] f = ConvertByteToFloat(bytes_music);
        AudioClip audioClip = AudioClip.Create("testSound", f.Length, 1, 44100, false, false);
        audioClip.SetData(f, 0);
        AudioSource.PlayClipAtPoint(audioClip, args.sender.position, 1.0f);
        Reference.Tell(args.sender.networkPlayer, "Successfully created sound");
      }
      catch(Exception ex)
            {
        Reference.Tell(args.sender.networkPlayer, $"Error: {ex}");
            }
    }


Function ConvertByteToFloat(bytes_music) :
private float[] ConvertByteToFloat(byte[] array)
    {
      float[] floatArr = new float[array.Length / 4];
      for (int i = 0; i < floatArr.Length; i++)
      {
        if (BitConverter.IsLittleEndian)
          Array.Reverse(array, i * 4, 4);
        floatArr[i] = BitConverter.ToSingle(array, i * 4) / 0x80000000;
      }
      return floatArr;
    }


I'm loading an array of bytes from the clip.ogg file (tried with mp3 as well) into the bytes_music variable.
Audio plays, but only noise (

Question, what did I do wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GFX Data, 2020-08-10
@ShockWave2048

Try loading via UnityWebRequestMultimedia.GetAudioClip("file://", AudioType.OGGVORBIS).
It supports uploading local files via the "file://" prefix.
https://forum.unity.com/threads/load-mp3-files-sav...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question