android 在 TarsosDSP 库中使用 FFT

Using FFT in TarsosDSP library in android

我刚开始使用 TarsosDSP 作为 android,我不知道如何使用 FFT。谁能给我提供样品?我只想读取一个文件并获取它的 FFT 输出。

试试这个代码:

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

它基于 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 到您项目的 assets 文件夹。

别忘了添加

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

AndroidManifest.xml(并且还为 targetSdkVersion 提供高于 21 的运行时权限)

PS。如果 bufferSize 等于源文件中的样本数(或更大),则可以对整个文件进行 FFT。