Search code examples
javaaudiofilter

How do I low-pass and high-pass filter audio in Java using a double[] array


I've searched pages for how to do this and found code in C but not java.

Example for C: https://kiritchatterjee.wordpress.com/2014/11/10/a-simple-digital-low-pass-filter-in-c/

This link above doesn't mention arrays because they are probably doing it as something where audio is streaming through a microphone for example, which I'm not looking to do, I'm looking to low-pass or high-pass a piece of audio and then save the result of it being low/high passed.

NOTE: I'm just adding [] next to array to make the explanation more visibly clear to those reading

Essentially what I'd like to do is the following:

  • Read a .wav file using java code

  • Covert the .wav data into a double [] array (by converting a byte [] array to a double [] array using StdAudio library)

  • From there I'd like to high-pass/low-pass the audio data - applying it to the double [] array

  • Once the high passing or low passing is applied to the double [] array then I will end up with a brand new double [] array

Error that I get for the code that's in the for loop:

Operator '-' cannot be applied to 'double', 'double[]'

Other issue:

I don't actually know whether my code in the for loop is going to low-pass the audio even if I don't get errors.

Code:

import StdAudio.*; 

public class PassAudio
{

    public static int RawData;
    public static double SmoothData;
    public static double LPF_Beta = 0.025; // 0<ß<1

    public static void main(String[] args) 
    {
        //read the file and convert it to a double array
        
        double[] music = 

        StdAudio.read("https://introcs.cs.princeton.edu/java/stdlib/BaseDrum.wav");
        
        double [] lowPassedAudio = new double [music.length];

        //low pass the audio
        for(int i = 0; i < music.length; i++)
        {
                //high pass/low pass the audio data
                 lowPassedAudio [i] = lowPassedAudio [i] - (LPF_Beta * 
                (lowPassedAudio [i] - music));
        }
        StdAudio.play(lowPassedAudio);                    
    }
}

Solution

  • In lowPassedAudio[i] = lowPassedAudio[i] - (LPF_Beta * (lowPassedAudio[i] - music)); You're trying to subtract an entire array (music) by lowPassedAudio[i] which is a double. You need to index music.

    public static void main(String[] args) {
        double[] music = StdAudio.read("https://introcs.cs.princeton.edu/java/stdlib/BaseDrum.wav");
    
        double[] lowPassedAudio = new double[music.length];
    
        lowPassedAudio[0] = music[0];
    
        for (int i = 1; i < music.length; i++) {
            lowPassedAudio[i] = lowPassedAudio[i - 1] + LPF_Beta * (music[i] - lowPassedAudio[i - 1]);
        }
    
        StdAudio.play(lowPassedAudio);
    }