Get PCM data from an mp3 track with a desired number of samples - AudioClip.GetData and mpg123
I've been trying to retrieve the raw PCM data from a music track stored in an mp3 format using the AudioClip.GetData function. Unfortunately the returned array is filled with 0s.
The track, however, is played properly: the data is loaded in the AudioClip using SetData with the output of a function from the mpg123 library as a parameter.
Here's a fragment of @KoningStoma's code that I used to test it.
myClip = AudioClip.Create ("myClip", lengthSamples, intChannels, intRate, false);
int importIndex = 0;
//List<float> trackPCM = new List<float>();
while (0 == MPGImport.mpg123_read(handle_mpg, Buffer, FrameSize, out done))
{
float[] fArray;
fArray = ByteToFloat (Buffer);
//trackPCM.AddRange(fArray);
myClip.SetData (fArray, (importIndex*fArray.Length)/2);
importIndex++;
}
//float [] trackPCMArray = trackPCM.ToArray ();
//myClip.SetData (trackPCMArray, 0);
MPGImport.mpg123_close (handle_mpg);
audioSource.clip = myClip;
audioSource.loop = false;
audioSource.Play ();
float[] dataCopy = new float [numSamples];
myClip.GetData ( dataCopy , 0 );
I've read the reference pages for both mpg123 and GetData but I don't fully understand what's the proper way to obtain the raw PCM data sampled across particular intervals.
I'll need more than 8192 samples so getSpectrumData() isn't an option, getData() simply returns 0s and mpg123_read() yields an array with channels * track sampling frequency * time samples which is way more than I need.
Is there a different way to get the raw PCM data of a track with a custom number of samples using any of these functions?
If not, would manually sampling the array obtained from mpg123_read() be a good solution?
Thank you in advance.
Answer by ChurrosBllack · Sep 01, 2016 at 01:50 PM
It may be a stupid question but are you using a compressed Audio File? Cause if so, you need to choose "Decompress on Load" in the Load Type of your clip :)