使用FFT复杂的阶级获取频率WAV音频 [英] Get frequency wav audio using FFT and Complex class

查看:281
本文介绍了使用FFT复杂的阶级获取频率WAV音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它已经问了很多,但我还是坚持落实有关在Android FFT类 我需要用处理我的音频数据的FFT ...

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...

我已经在这里<读了几乎同样的问题href="http://stackoverflow.com/questions/7604011/how-can-i-get-frequency-data-from-pcm-using-fft">How我可以从PCM使用FFT 获取频率数据 这里如何从FFT结果得到的频率? 而更多的问题,但仍然没有找到答案,即使我试图给出的答案...

I already read the almost same question here How can I get frequency data from PCM using FFT and here How to get frequency from fft result? and more questions but still find no answer even after I tried the answers given...

FFT类正在使用: http://www.cs.princeton.edu/introcs/97data/FFT.java

FFT Class I'm using: http://www.cs.princeton.edu/introcs/97data/FFT.java

复杂类去用它:的http:// introcs。 cs.princeton.edu/java/97data/Complex.java.html

下面是我的code

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;

public class Latihan extends Activity{
        private static final int RECORDER_BPP = 16;
        private static final String AUDIO_RECORDER_FILE_EXT_WAV = ".wav";
        private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
        private static final String AUDIO_RECORDER_TEMP_FILE = "record_temp.raw";
        private static final int RECORDER_SAMPLERATE = 44100;
        private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
        private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
        short[] audioData;

        private AudioRecord recorder = null;
        private int bufferSize = 0;
        private Thread recordingThread = null;
        private boolean isRecording = false;
        Complex[] fftTempArray;
        Complex[] fftArray;
        int[] bufferData;
        int bytesRecorded;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.p1);

        setButtonHandlers();
        enableButtons(false);

        bufferSize = AudioRecord.getMinBufferSize
                (RECORDER_SAMPLERATE,RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING)*3;

        audioData = new short [bufferSize]; //short array that pcm data is put into.

        }


    private void setButtonHandlers() {
        ((Button)findViewById(R.id.btStart)).setOnClickListener(btnClick);
        ((Button)findViewById(R.id.btStop)).setOnClickListener(btnClick);
        }


        private void enableButton(int id,boolean isEnable){
                ((Button)findViewById(id)).setEnabled(isEnable);
        }

        private void enableButtons(boolean isRecording) {
                enableButton(R.id.btStart,!isRecording);
                enableButton(R.id.btStop,isRecording);
        }

        private String getFilename(){
                String filepath = Environment.getExternalStorageDirectory().getPath();
                File file = new File(filepath,AUDIO_RECORDER_FOLDER);

                if(!file.exists()){
                        file.mkdirs();
                }

                return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + AUDIO_RECORDER_FILE_EXT_WAV);
        }


        public void convert(){



        }

        public void calculate(){
            Complex[] fftTempArray = new Complex[bufferSize];
            for (int i=0; i<bufferSize; i++)
            {
                fftTempArray[i] = new Complex(audioData[i], 0);
            }
            Complex[] fftArray = FFT.fft(fftTempArray);

            double[] micBufferData = new double[bufferSize];
            final int bytesPerSample = 2; 
            final double amplification = 100.0; 
            for (int index = 0, floatIndex = 0; index < bytesRecorded - bytesPerSample + 1; index += bytesPerSample, floatIndex++) {
                double sample = 0;
                for (int b = 0; b < bytesPerSample; b++) {
                    int v = bufferData[index + b];
                    if (b < bytesPerSample - 1 || bytesPerSample == 1) {
                        v &= 0xFF;
                    }
                    sample += v << (b * 8);
                }
                double sample32 = amplification * (sample / 32768.0);
                micBufferData[floatIndex] = sample32;
            }


     }


        private String getTempFilename(){
                String filepath = Environment.getExternalStorageDirectory().getPath();
                File file = new File(filepath,AUDIO_RECORDER_FOLDER);

                if(!file.exists()){
                        file.mkdirs();
                }

                File tempFile = new File(filepath,AUDIO_RECORDER_TEMP_FILE);

                if(tempFile.exists())
                        tempFile.delete();

                return (file.getAbsolutePath() + "/" + AUDIO_RECORDER_TEMP_FILE);
        }

        private void startRecording(){
            recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                                                RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);

                recorder.startRecording();

                isRecording = true;

                recordingThread = new Thread(new Runnable() {

                        public void run() {
                                writeAudioDataToFile();
                        }
                },"AudioRecorder Thread");

                recordingThread.start();
        }

        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(AudioRecord.ERROR_INVALID_OPERATION != read){
                                        try {
                                                os.write(data);
                                        } catch (IOException e) {
                                                e.printStackTrace();
                                        }
                                }
                        }

                        try {
                                os.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                }
        }

        private void stopRecording(){
                if(null != recorder){
                        isRecording = false;

                        recorder.stop();
                        recorder.release();

                        recorder = null;
                        recordingThread = null;
                }

                copyWaveFile(getTempFilename(),getFilename());
               // deleteTempFile();
        }

        private void deleteTempFile() {
                File file = new File(getTempFilename());
                file.delete();
        }

        private void copyWaveFile(String inFilename,String outFilename){
                FileInputStream in = null;
                FileOutputStream out = null;
                long totalAudioLen = 0;
                long totalDataLen = totalAudioLen + 36;
                long longSampleRate = RECORDER_SAMPLERATE;
                int channels = 2;
                long byteRate = RECORDER_BPP * RECORDER_SAMPLERATE * channels/8;

                byte[] data = new byte[bufferSize];

                try {
                        in = new FileInputStream(inFilename);
                        out = new FileOutputStream(outFilename);
                        totalAudioLen = in.getChannel().size();
                        totalDataLen = totalAudioLen + 36;

                        AppLog.logString("File size: " + totalDataLen);

                        WriteWaveFileHeader(out, totalAudioLen, totalDataLen,
                                        longSampleRate, channels, byteRate);

                        while(in.read(data) != -1){
                                out.write(data);
                        }

                        in.close();
                        out.close();
                } catch (FileNotFoundException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
        }

        private void WriteWaveFileHeader(
                        FileOutputStream out, long totalAudioLen,
                        long totalDataLen, long longSampleRate, int channels,
                        long byteRate) throws IOException {
            //another code    

        }

        private View.OnClickListener btnClick = new View.OnClickListener() {
                public void onClick(View v) {
                     switch(v.getId()){
                              case R.id.btStart:{
                                        AppLog.logString("Start Recording");
                                        enableButtons(true);
                                        startRecording();
                                        break;
                                }
                                case R.id.btStop:{
                                    AppLog.logString("Stop Recording");
                                        enableButtons(false);
                                        stopRecording();
                                        calculate();
                                        break;

                                }
                        }
                }
        }; 
}

我承担audioData数组包含原始音频数据,但我的code捕获异常并返回N不是2的幂

I assume the audioData array contains the raw audio data,but my code catch the exception and return "N is not a power of 2"

它是什么错我的code? 我该如何将它传递给FFT.java类,并获得fftResult ??

Is it anything wrong with my code ?? How do I pass it to FFT.java class and get the fftResult ??

或者是有时间域数据的频率转换数据的其他方式,更容易?

Or is there an other way to convert time domain data to frequency data that more easier ?

这是一个几个月,因为我被卡住这个......我的项目是过比较2个音频* .wav文件, 任何帮助将是AP preciated ...:)

It's been a few months since I get stuck with this... My project is too compare 2 audio of *.wav files, Any help would be appreciated... :)

推荐答案

我已经找到了答案...:)

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();
                }
        }
}

这篇关于使用FFT复杂的阶级获取频率WAV音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆