package com.yonge.audio.analysis.detector;

import com.yonge.audio.analysis.Complex;
import com.yonge.audio.analysis.FFT;

public class FrequencyDetector {

	private float[] samples;

	private boolean isUseHanmingWindow;

	private float sampleRate;

	public FrequencyDetector(float[] samples, float sampleRate, boolean isUseHanmingWindow) {
		this.samples = samples;
		this.sampleRate = sampleRate;
		this.isUseHanmingWindow = isUseHanmingWindow;
	}

	public double getFrequency() {

		if (isUseHanmingWindow) {
			// 加汉明窗
			hamming(samples);
		}

		Complex[] complex = new Complex[samples.length];

		for (int i = 0; i < samples.length; i++) {
			complex[i] = new Complex(samples[i], 0);
		}
		Complex[] result = FFT.fft(complex);

		double maxMagnitude = result[0].abs();
		int maxIndex = 0;

		for (int i = 1; i < result.length / 2; i++) {
			if (maxMagnitude < result[i].abs()) {
				maxMagnitude = result[i].abs();
				maxIndex = i;
			}
		}

		return maxIndex * sampleRate / result.length;
	}

	private void hamming(float[] samples) {
		for (int i = 0; i < samples.length; i++) {
			samples[i] *= (0.54f - 0.46f * Math.cos((2 * Math.PI) * i / (samples.length - 1)));
		}
	}
}
