java 如何将 16 位 PCM 音频字节数组转换为双精度或浮点数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10324355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert 16-bit PCM audio byte-array to double or float array?
提问by soren.qvist
I'm trying to perform Fast Fourier Transform on a .3gpp audio file. The file contains a small 5 second recording in 44100kHz from the phones microphone.
我正在尝试对 .3gpp 音频文件执行快速傅立叶变换。该文件包含来自手机麦克风的 44100kHz 的 5 秒小录音。
Every Java FFT algorithm I can find only takes double[], float[] or Complex[] inputs, for obvious reasons, but I'm reading in the audio file in a byte-array, so I'm kind of confused as to where I go from here. The only thing I could find is the answer to a previous question:
出于显而易见的原因,我能找到的每个 Java FFT 算法都只采用 double[]、float[] 或 Complex[] 输入,但我正在读取字节数组中的音频文件,所以我有点困惑我从哪里去。我唯一能找到的是上一个问题的答案:
Android audio FFT to retrieve specific frequency magnitude using audiorecord
Android音频FFT使用audiorecord检索特定频率幅度
But I'm unsure as to wether or not this is the correct procedure. Anyone with any insight?
但我不确定这是否是正确的程序。任何有洞察力的人?
回答by mwengler
There is no alternative. You have to run a loop and cast each element of the array separately.
没有替代。您必须运行一个循环并分别转换数组的每个元素。
I do the same thing for shorts that I fft as floats:
我对短裤做同样的事情,我把它当作花车:
public static float[] floatMe(short[] pcms) {
float[] floaters = new float[pcms.length];
for (int i = 0; i < pcms.length; i++) {
floaters[i] = pcms[i];
}
return floaters;
}
EDIT 4/26/2012 based on comments
根据评论编辑 4/26/2012
If you really do have 16 bit PCM but have it as a byte[], then you can do this:
如果您确实有 16 位 PCM 但将其作为字节 [],那么您可以这样做:
public static short[] shortMe(byte[] bytes) {
short[] out = new short[bytes.length / 2]; // will drop last byte if odd number
ByteBuffer bb = ByteBuffer.wrap(bytes);
for (int i = 0; i < out.length; i++) {
out[i] = bb.getShort();
}
return out;
}
then
然后
float[] pcmAsFloats = floatMe(shortMe(bytes));
Unless you are working with a weird and badly designed class that gave you the byte array in the first place, the designers of that class should have packed the bytes to be consistent with the way Java converts bytes (2 at a time) to shorts.
除非您正在使用一个奇怪且设计糟糕的类,它首先为您提供了字节数组,否则该类的设计者应该将字节打包以与 Java 将字节(一次 2 个)转换为 short 的方式一致。
回答by Kyle
byte[] yourInitialData;
double[] yourOutputData = ByteBuffer.wrap(bytes).getDouble()