在java

时间:2016-09-02 15:07:40

标签: java signal-processing fft spectrogram

经过研究和大量的试验和错误,我已经说到我可以构建一个谱图,我认为它具有权利和错误的元素。

1。首先,我将.wav文件读入字节数组并仅提取数据部分。

2. 我将字节数组转换为双数组,该数组取右右声道的平均值。我还注意到1个通道的1个样本由2个字节组成。所以,4个字节变为1个双倍。

3. 对于某个窗口大小为2的幂,我从here应用FFT并获得频域中的幅度。这是频谱图像的垂直条带。

4. 我以相同的窗口大小重复执行此操作并重叠整个数据并获取光谱图。

以下是将.wav读入双数组

的代码
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

public class readWAV2Array {

    private byte[] entireFileData;

    //SR = sampling rate
    public double getSR(){
        ByteBuffer wrapped = ByteBuffer.wrap(Arrays.copyOfRange(entireFileData, 24, 28)); // big-endian by default
        double SR = wrapped.order(java.nio.ByteOrder.LITTLE_ENDIAN).getInt();
        return SR;
    }

    public readWAV2Array(String filepath, boolean print_info) throws IOException{
        Path path = Paths.get(filepath);
        this.entireFileData = Files.readAllBytes(path);

        if (print_info){

        //extract format
        String format = new String(Arrays.copyOfRange(entireFileData, 8, 12), "UTF-8");

        //extract number of channels
        int noOfChannels = entireFileData[22];
        String noOfChannels_str;
        if (noOfChannels == 2)
            noOfChannels_str = "2 (stereo)";
        else if (noOfChannels == 1)
            noOfChannels_str = "1 (mono)";
        else
            noOfChannels_str = noOfChannels + "(more than 2 channels)";

        //extract sampling rate (SR)
        int SR = (int) this.getSR();

        //extract Bit Per Second (BPS/Bit depth)
        int BPS = entireFileData[34];

        System.out.println("---------------------------------------------------");
        System.out.println("File path:          " + filepath);
        System.out.println("File format:        " + format);
        System.out.println("Number of channels: " + noOfChannels_str);
        System.out.println("Sampling rate:      " + SR);
        System.out.println("Bit depth:          " + BPS);
        System.out.println("---------------------------------------------------");

        }
    }

    public double[] getByteArray (){
        byte[] data_raw = Arrays.copyOfRange(entireFileData, 44, entireFileData.length);
        int totalLength = data_raw.length;

        //declare double array for mono
        int new_length = totalLength/4;
        double[] data_mono = new double[new_length];

        double left, right;
        for (int i = 0; i < new_length; i++){
            left = ((data_raw[i] & 0xff) << 8) | (data_raw[i+1] & 0xff);
            right = ((data_raw[i+2] & 0xff) << 8) | (data_raw[i+3] & 0xff);
            data_mono[i] = (left+right)/2.0;
        }       
        return data_mono;
    }
}

以下代码是要运行的主程序

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.imageio.ImageIO;

public class App {

    public static Color getColor(double power) {
        double H = power * 0.4; // Hue (note 0.4 = Green, see huge chart below)
        double S = 1.0; // Saturation
        double B = 1.0; // Brightness

        return Color.getHSBColor((float)H, (float)S, (float)B);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String filepath = "audio_work/Sine_Sweep_Full_Spectrum_20_Hz_20_kHz_audiocheck.wav";
        try {

            //get raw double array containing .WAV data
            readWAV2Array audioTest = new readWAV2Array(filepath, true);
            double[] rawData = audioTest.getByteArray();
            int length = rawData.length;

            //initialize parameters for FFT
            int WS = 2048; //WS = window size
            int OF = 8;    //OF = overlap factor
            int windowStep = WS/OF;

            //calculate FFT parameters
            double SR = audioTest.getSR();
            double time_resolution = WS/SR;
            double frequency_resolution = SR/WS;
            double highest_detectable_frequency = SR/2.0;
            double lowest_detectable_frequency = 5.0*SR/WS;

            System.out.println("time_resolution:              " + time_resolution*1000 + " ms");
            System.out.println("frequency_resolution:         " + frequency_resolution + " Hz");
            System.out.println("highest_detectable_frequency: " + highest_detectable_frequency + " Hz");
            System.out.println("lowest_detectable_frequency:  " + lowest_detectable_frequency + " Hz");

            //initialize plotData array
            int nX = (length-WS)/windowStep;
            int nY = WS;
            double[][] plotData = new double[nX][nY]; 

            //apply FFT and find MAX and MIN amplitudes

            double maxAmp = Double.MIN_VALUE;
            double minAmp = Double.MAX_VALUE;

            double amp_square;

            double[] inputImag = new double[length];

            for (int i = 0; i < nX; i++){
                Arrays.fill(inputImag, 0.0);
                double[] WS_array = FFT.fft(Arrays.copyOfRange(rawData, i*windowStep, i*windowStep+WS), inputImag, true);
                for (int j = 0; j < nY; j++){
                    amp_square = (WS_array[2*j]*WS_array[2*j]) + (WS_array[2*j+1]*WS_array[2*j+1]);
                    if (amp_square == 0.0){
                        plotData[i][j] = amp_square;
                    }
                    else{
                        plotData[i][j] = 10 * Math.log10(amp_square);
                    }

                    //find MAX and MIN amplitude
                    if (plotData[i][j] > maxAmp)
                        maxAmp = plotData[i][j];
                    else if (plotData[i][j] < minAmp)
                        minAmp = plotData[i][j];

                }
            }

            System.out.println("---------------------------------------------------");
            System.out.println("Maximum amplitude: " + maxAmp);
            System.out.println("Minimum amplitude: " + minAmp);
            System.out.println("---------------------------------------------------");

            //Normalization
            double diff = maxAmp - minAmp;
            for (int i = 0; i < nX; i++){
                for (int j = 0; j < nY; j++){
                    plotData[i][j] = (plotData[i][j]-minAmp)/diff;
                }
            }

            //plot image
            BufferedImage theImage = new BufferedImage(nX, nY, BufferedImage.TYPE_INT_RGB);
            double ratio;
            for(int x = 0; x<nX; x++){
                for(int y = 0; y<nY; y++){
                    ratio = plotData[x][y];

                    //theImage.setRGB(x, y, new Color(red, green, 0).getRGB());
                    Color newColor = getColor(1.0-ratio);
                    theImage.setRGB(x, y, newColor.getRGB());
                }
            }
            File outputfile = new File("saved.png");
            ImageIO.write(theImage, "png", outputfile);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

但是,我从.wav获得的图像从20-20kHz播放清晰的声音是这样的:

颜色显示声音红色的强度(高) - >绿色(低)

enter image description here

如右图所示,它应如下图所示:

enter image description here

如果我能对项目得到任何正确/改进/建议,我将非常感激。提前感谢您对我的问题发表评论。

1 个答案:

答案 0 :(得分:9)

幸运的是,你似乎拥有的权利多于错误。

导致额外红线的第一个和主要问题是由于您在readWAV2Array.getByteArray中解码数据的方式。由于样本跨越4个字节,因此必须以4的倍数(例如,样本0的字节0,1,2,3,样本1的字节4,5,6,7)进行索引,否则您将读取4个字节的重叠块(例如,样本0的字节0,1,2,3,样本1的字节1,2,3,4)。此转换的另一个原因是您必须将结果明确地转换为签名的short类型,然后才能将其分配给leftright(类型为double} )以便从无符号字节中获得带符号的16位结果。这应该会给你一个转换循环,如下所示:

for (int i = 0; 4*i+3 < totalLength; i++){
  left = (short)((data_raw[4*i+1] & 0xff) << 8) | (data_raw[4*i] & 0xff);
  right = (short)((data_raw[4*i+3] & 0xff) << 8) | (data_raw[4*i+2] & 0xff);
  data_mono[i] = (left+right)/2.0;
}       

此时你应该开始得到一个强大的线条代表你的20Hz-20kHz啁啾的情节:

fixed decoding

但是你应该注意到你实际得到2行。这是因为对于实值信号,频谱具有厄米特对称性。因此,奈奎斯特频率以上的频谱幅度(采样速率的一半,在这种情况下为44100Hz / 2)是低于奈奎斯特频率的频谱的冗余反射。只需将nYmain的定义更改为:

,即可将非冗余部分绘制在奈奎斯特频率以下
int nY = WS/2 + 1;

并会给你:

only non-redundant spectrum

几乎我们正在寻找的东西,但频率越来越高的扫描会产生一个数字正在减少的数字。那是因为你的索引使得索引0处的0Hz频率(图中的顶部)和指数nY-1处的22050Hz频率(图中的底部)。要翻转图形并在底部获得更常见的0Hz,在顶部获得22050Hz,您可以更改要使用的索引:

plotData[i][nY-j-1] = 10 * Math.log10(amp_square);

现在你应该有一个看起来像你期望的情节(尽管有不同的颜色图):

0Hz at the bottom

最后一点:虽然我理解你打算避免在转换中将0的对数记录为分贝,但在这种特定情况下将输出设置为线性刻度幅度可能会产生意外结果。相反,我会为保护选择截止阈值幅度:

// select threshold based on the expected spectrum amplitudes
// e.g. 80dB below your signal's spectrum peak amplitude
double threshold = 1.0;
// limit values and convert to dB
plotData[i][nY-j-1] = 10 * Math.log10(Math.max(amp_square,threshold));