Using FFT in TarsosDSP library in android

android, fft, tarsosdsp

Solution

Try this code:

    new AndroidFFMPEGLocator(this);
    new Thread(new Runnable() {
        @Override
        public void run() {
            File externalStorage = Environment.getExternalStorageDirectory();
            File sourceFile = new File(externalStorage.getAbsolutePath() , "/440.mp3");

            final int bufferSize = 4096;
            final int fftSize = bufferSize / 2;
            final int sampleRate = 44100;

            AudioDispatcher audioDispatcher;
            audioDispatcher = AudioDispatcherFactory.fromPipe(sourceFile.getAbsolutePath(), sampleRate, bufferSize, 0);
            audioDispatcher.addAudioProcessor(new AudioProcessor() {

                FFT fft = new FFT(bufferSize);
                final float[] amplitudes = new float[fftSize];

                @Override
                public boolean process(AudioEvent audioEvent) {
                    float[] audioBuffer = audioEvent.getFloatBuffer();
                    fft.forwardTransform(audioBuffer);
                    fft.modulus(audioBuffer, amplitudes);

                    for (int i = 0; i < amplitudes.length; i++) {
                        Log.d(TAG, String.format("Amplitude at %3d Hz: %8.3f", (int) fft.binToHz(i, sampleRate) , amplitudes[i]));
                    }

                    return true;
                }

                @Override
                public void processingFinished() {

                }
            });
            audioDispatcher.run();
        }
    }).start();

It based on TarsosDSP Manual (page 12) and calculates and shows in log FFT for each `bufferSize` of 440.mp3 file (test 440Hz tone) on External storage (SD card). You should add TarsosDSP-Android-2.3.jar (or newer) from here to `libs` folder of your project (and add it as a library) and corresponding to your device ffmpeg library (armeabi-v7a_ffmpeg, armeabi-v7a-neon_ffmpeg or x86_ffmpeg) from here to `assets` folder of your project.

And don't forget add

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

to `AndroidManifest.xml` (and also give runtime permissions for `targetSdkVersion` higher then 21)

PS. You can give FFT for whole file if `bufferSize` will be equals to number of samples in source file (or bigger).

Problem

I'm just starting to use TarsosDSP for android and I can't figure out how to use FFT. Can anyone provide me with a sample? I just wanna read a file and get FFT output of it.

Original source