Search code examples
javaandroidmatlabaudio-processing

matlab to android conversion to calculate energy


I have to convert a matlab code into Android. This matlab code contains energy calculation as shown below:

first I read the audio file into matrix x, and the sample frequency into fs, and then calculate the energy for each window:

[x, fs] = wavread('C:\1359873105438.wav')
energy=energy+sum(x(1:fs).^2)*Tss;

I am not sure how to convert this into Android/Java.

Have you been through this before? please help me to get over this problem.

thanks in advance for your help


Solution

  • Essentially, you have to do something like this:

    double x;//Read Wave in here
    for (i=0;i<x.length;i++)
    {
        energy+=Tss*(x[i]^2);
    }
    

    How to read the wave files borrowed from this article.

    public class ReadExample
    {
       public static void main(String[] args)
       {
          try
          {
             // Open the wav file specified as the first argument
             WavFile wavFile = WavFile.openWavFile(new File(args[0]));
    
             // Get the number of audio channels in the wav file
             int numChannels = wavFile.getNumChannels();
    
             // Create a buffer of 100 frames
             double[] buffer = new double[100 * numChannels];
    
             int framesRead;
    
             do
             {
                // Read frames into buffer
                framesRead = wavFile.readFrames(buffer, 100);
    
                // Loop through frames and look for minimum and maximum value
                for (int s=0 ; s<framesRead * numChannels ; s++)
                {
                   //This is where you put the your code in
                }
             }
             while (framesRead != 0);
    
             // Close the wavFile
             wavFile.close();
          }
          catch (Exception e)
          {
             System.err.println(e);
          }
       }
    }
    

    Bottom line is, there isn't a nice clean way to do it like there is in matlab. There isn't even a function to directly read in a wave file. Still, it's relatively straight forward, using the WavFile class the website provides.