|
1 | 1 | package com.thealgorithms.audiofilters; |
2 | 2 |
|
3 | 3 | /** |
4 | | - * Exponential Moving Average (EMA) Filter for smoothing audio signals. |
5 | | - * |
6 | | - * <p>This filter applies an exponential moving average to a sequence of audio |
7 | | - * signal values, making it useful for smoothing out rapid fluctuations. |
8 | | - * The smoothing factor (alpha) controls the degree of smoothing. |
9 | | - * |
10 | | - * <p>Based on the definition from |
11 | | - * <a href="https://en.wikipedia.org/wiki/Moving_average">Wikipedia link</a>. |
| 4 | + * EMA Filter for audio signal smoothing. |
| 5 | + * Formula: EMA[i] = alpha * signal[i] + (1-alpha) * EMA[i-1] |
12 | 6 | */ |
13 | 7 | public class EMAFilter { |
14 | 8 | private final double alpha; |
15 | | - private double emaValue; |
16 | | - /** |
17 | | - * Constructs an EMA filter with a given smoothing factor. |
18 | | - * |
19 | | - * @param alpha Smoothing factor (0 < alpha <= 1) |
20 | | - * @throws IllegalArgumentException if alpha is not in (0, 1] |
21 | | - */ |
| 9 | + private double ema; |
| 10 | + |
22 | 11 | public EMAFilter(double alpha) { |
23 | | - if (alpha <= 0 || alpha > 1) { |
24 | | - throw new IllegalArgumentException("Alpha must be between 0 and 1."); |
25 | | - } |
| 12 | + if (alpha <= 0 || alpha > 1) throw new IllegalArgumentException("Alpha must be in (0,1]"); |
26 | 13 | this.alpha = alpha; |
27 | | - this.emaValue = 0.0; |
28 | 14 | } |
29 | | - /** |
30 | | - * Applies the EMA filter to an audio signal array. |
31 | | - * |
32 | | - * @param audioSignal Array of audio samples to process |
33 | | - * @return Array of processed (smoothed) samples |
34 | | - */ |
35 | | - public double[] apply(double[] audioSignal) { |
36 | | - if (audioSignal.length == 0) { |
37 | | - return new double[0]; |
38 | | - } |
39 | | - double[] emaSignal = new double[audioSignal.length]; |
40 | | - emaValue = audioSignal[0]; |
41 | | - emaSignal[0] = emaValue; |
42 | | - for (int i = 1; i < audioSignal.length; i++) { |
43 | | - emaValue = alpha * audioSignal[i] + (1 - alpha) * emaValue; |
44 | | - emaSignal[i] = emaValue; |
| 15 | + |
| 16 | + public double[] apply(double[] signal) { |
| 17 | + if (signal.length == 0) return new double[0]; |
| 18 | + |
| 19 | + double[] result = new double[signal.length]; |
| 20 | + ema = result[0] = signal[0]; |
| 21 | + |
| 22 | + for (int i = 1; i < signal.length; i++) { |
| 23 | + ema = alpha * signal[i] + (1 - alpha) * ema; |
| 24 | + result[i] = ema; |
45 | 25 | } |
46 | | - return emaSignal; |
| 26 | + return result; |
47 | 27 | } |
48 | 28 | } |
0 commit comments