Skip to content

Commit c910b86

Browse files
committed
Reuse window filter, avoid creation of new one each time
1 parent 466e97f commit c910b86

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

sound-recorder-n-spectrum-analyzer/src/main/java/by/andd3dfx/capturesound/fft/FrequencyScanner.java

+11-5
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
*/
1414
public class FrequencyScanner {
1515

16+
private double[] windowFilter = new double[]{};
17+
1618
public FrequencyInfoContainer detectFrequency(byte[] audioData, int sampleRate) {
1719
short[] sampleData = new short[audioData.length / 2];
1820
ByteBuffer.wrap(audioData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(sampleData);
@@ -69,7 +71,7 @@ private double[] applyWindow(short[] input) {
6971
var len = input.length;
7072
double[] res = new double[len];
7173

72-
double[] windowFilter = buildHammingWindow(len);
74+
rebuildHammingWindowIfNeeded(len);
7375
for (int i = 0; i < len; ++i) {
7476
res[i] = (double) input[i] * windowFilter[i];
7577
}
@@ -83,11 +85,15 @@ private double[] applyWindow(short[] input) {
8385
*
8486
* @param size the sample size for which the filter will be created
8587
*/
86-
private double[] buildHammingWindow(int size) {
87-
var res = new double[size];
88+
private void rebuildHammingWindowIfNeeded(int size) {
89+
// Build new window only if requested size differs from size of existing window
90+
if (windowFilter.length == size) {
91+
return;
92+
}
93+
94+
windowFilter = new double[size];
8895
for (int i = 0; i < size; ++i) {
89-
res[i] = 0.54 - 0.46 * Math.cos(2 * Math.PI * i / (size - 1.0));
96+
windowFilter[i] = 0.54 - 0.46 * Math.cos(2 * Math.PI * i / (size - 1.0));
9097
}
91-
return res;
9298
}
9399
}

0 commit comments

Comments
 (0)