Hello,
I have a code in which i get AudioData byte[ ]
I want to convert it to a List of Clips
I Know the Data are ok, because i can create files in .mp3
But i would like to avoid write/Delete files…
So I try to pass the datas to a wrapperlike this:
using System;
using System.IO;
using UnityEngine;
namespace Flippit
{
public static class WavUtility
{
public static AudioClip ToAudioClip(byte[] audioData, int offset, int length, int lengthSamples, int frequency, bool isStereo)
{
if (length <= 0 || audioData == null)
{
return null;
}
float[] audioFloat = new float[lengthSamples * (isStereo ? 2 : 1)];
int subChunk1Size = 16;
int audioFormat = 1; // PCM
int numChannels = isStereo ? 2 : 1;
int bitsPerSample = 16;
int byteRate = frequency * numChannels * bitsPerSample / 8;
int blockAlign = numChannels * bitsPerSample / 8;
int subChunk2Size = lengthSamples * numChannels * bitsPerSample / 8;
int chunkSize = 36 + subChunk2Size;
using MemoryStream stream = new();
using BinaryWriter writer = new(stream);
writer.Write(new char[] { 'R', 'I', 'F', 'F' });
writer.Write(chunkSize);
writer.Write(new char[] { 'W', 'A', 'V', 'E' });
writer.Write(new char[] { 'f', 'm', 't', ' ' });
writer.Write(subChunk1Size);
writer.Write(audioFormat);
writer.Write(numChannels);
writer.Write(frequency);
writer.Write(byteRate);
writer.Write(blockAlign);
writer.Write(bitsPerSample);
writer.Write(new char[] { 'd', 'a', 't', 'a' });
writer.Write(subChunk2Size);
for (int i = 0; i < lengthSamples; i++)
{
float sample = BitConverter.ToSingle(audioData, i * 4 + offset);
audioFloat[i] = sample;
}
AudioClip audioClip = AudioClip.Create("TempClip", lengthSamples, isStereo ? 2 : 1, frequency, false);
audioClip.SetData(audioFloat, 0);
return audioClip;
}
}
}
each time I try, I get the following error message:
ArgumentException: Length of created clip must be larger than 0
Of course it should, I checked AudioData as A length, and each converted float also
So I’m wondering what i should do to get the correct conversion.