Get frequency wav audio using FFT and Complex class

前端 未结 2 1431
青春惊慌失措
青春惊慌失措 2020-12-01 11:45

It\'s been asked a lot, but I still stuck about implement FFT class on Android I need to process my audio data using FFT...

I already read the almost same question h

2条回答
  •  庸人自扰
    2020-12-01 12:02

    I already found the answer... :)

    I create method to calculate array value from audio...

    public double[] calculateFFT(byte[] signal)
        {           
            final int mNumberOfFFTPoints =1024;
            double mMaxFFTSample;
    
            double temp;
            Complex[] y;
            Complex[] complexSignal = new Complex[mNumberOfFFTPoints];
            double[] absSignal = new double[mNumberOfFFTPoints/2];
    
            for(int i = 0; i < mNumberOfFFTPoints; i++){
                temp = (double)((signal[2*i] & 0xFF) | (signal[2*i+1] << 8)) / 32768.0F;
                complexSignal[i] = new Complex(temp,0.0);
            }
    
            y = FFT.fft(complexSignal); // --> Here I use FFT class
    
            mMaxFFTSample = 0.0;
            mPeakPos = 0;
            for(int i = 0; i < (mNumberOfFFTPoints/2); i++)
            {
                 absSignal[i] = Math.sqrt(Math.pow(y[i].re(), 2) + Math.pow(y[i].im(), 2));
                 if(absSignal[i] > mMaxFFTSample)
                 {
                     mMaxFFTSample = absSignal[i];
                     mPeakPos = i;
                 } 
            }
    
            return absSignal;
    
        }
    

    Then I called it in class Write Audio..

    private void writeAudioDataToFile(){
    
            byte data[] = new byte[bufferSize];
            String filename = getTempFilename();
           FileOutputStream os = null;
    
            try {
                    os = new FileOutputStream(filename);
            } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            }
    
            int read = 0;                
            if(null != os){
                    while(isRecording){
                            read = recorder.read(data, 0, bufferSize);
                            if(read > 0){
                                absNormalizedSignal = calculateFFT(data); // --> HERE ^__^
                            }
    
                            if(AudioRecord.ERROR_INVALID_OPERATION != read){
                                    try {
                                            os.write(data);
                                    } catch (IOException e) {
                                            e.printStackTrace();
                                    }
                            }
                    }
    
                    try {
                            os.close();
                    } catch (IOException e) {
                            e.printStackTrace();
                    }
            }
    }
    

提交回复
热议问题