Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Basic FFT to identify frequency

  1. #1
    Junior Member
    Join Date
    Aug 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Basic FFT to identify frequency

    For some reason the frequencies are off....

    package com.overdrive.FreqFinder;
     
    import java.nio.ByteBuffer;
    import java.nio.ByteOrder;
     
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.TargetDataLine;
     
    import org.apache.commons.math3.complex.Complex;
    import org.apache.commons.math3.transform.DftNormalization;
    import org.apache.commons.math3.transform.FastFourierTransformer;
    import org.apache.commons.math3.transform.TransformType;
     
    public class AudioInput {
     
    	TargetDataLine 	microphone;
     
    	final int 		audioFrames= 4096;  //power ^ 2
     
    	final float 	sampleRate= 8000.0f;
    	final int 		bitsPerRecord= 16;		// div 32768 ?
    	final int 		channels= 1;
    	final boolean 	bigEndian = true;
    	final boolean 	signed= true;
     
    	byte 			byteData[]; 	// length=audioFrames * 2
    	double 			doubleData[];	// length=audioFrames only reals needed for apache lib.
     
    	AudioFormat 	format;
     
     
    	public AudioInput () {
     
    		byteData= new byte[audioFrames * 2];  //two bytes per audio frame, 16 bits
     
    		//doubleData= new double[audioFrames * 2];  // real & imaginary
    		doubleData= new double[audioFrames];  // only real for apache
     
     
    		System.out.print("Microphone initialization\n");
    		format = new AudioFormat(sampleRate, bitsPerRecord, channels, signed, bigEndian);
    		DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); // format is an AudioFormat object
     
    		if (!AudioSystem.isLineSupported(info)) {
    			System.err.print("isLineSupported failed");
    			System.exit(1);
    		}
     
    		try {
    			 microphone = (TargetDataLine) AudioSystem.getLine(info);
    		     microphone.open(format);
    		     System.out.print("Microphone opened with format: "+format.toString()+"\n");
    		     microphone.start();
    		}catch(Exception ex){
    			System.out.println("Microphone failed: "+ex.getMessage());
    			System.exit(1);
    		}
     
    	}
     
    	public int readPcm(){
     
    		int numBytesRead= 
    				microphone.read(byteData, 0, byteData.length);
    		if(numBytesRead!=byteData.length){
    			System.out.println("Warning: read less bytes than buffer size");
    			System.exit(1);
    		}
     
    		return numBytesRead;
    	}
     
     
    	public void byteToDouble(){
     
    		ByteBuffer buf= ByteBuffer.wrap(byteData);
    		buf.order(ByteOrder.BIG_ENDIAN);
    		int i=0; 
     
    		while(buf.remaining()>1){
    			short s = buf.getShort();
    			doubleData[ i ] = (new Short(s)).doubleValue() / 32768.0;
    			++i;
    		}
    	}
     
     
    	public void findFrequency(){
     
    		double frequency;
    		FastFourierTransformer transformer = new FastFourierTransformer(
    				DftNormalization.STANDARD);
     
    		Complex[] cmplx= transformer.transform(doubleData, TransformType.FORWARD);
     
    		double real;
    		double im;
    		double mag[] = new double[cmplx.length];
     
    		for(int i = 0; i < cmplx.length; i++){
                real = cmplx[i].getReal();
                im = cmplx[i].getImaginary();
                mag[i] = Math.sqrt((real * real) + (im*im));
            }
     
    		double peak = -1.0;
    		int index=-1;
            for(int i = 0; i < cmplx.length; i++){
                if(peak < mag[i]){
                    index=i;
                    peak= mag[i];
                }
            }
     
            frequency = (sampleRate * index) / audioFrames;
            System.out.print("Index: "+index+", Frequency: "+frequency+"\n");
     
    	}
     
    	public void printFreqs(){
    		for (int i=0; i<audioFrames; i++){
    			System.out.println("bin "+i+", freq: "+(sampleRate*i)/audioFrames);
    		}
    	}
     
     
     
    	public static void main(String[] args) {
    		AudioInput ai= new AudioInput();
     
     
    		int turns=10000;
     
    		while(turns-- > 0){
    			ai.readPcm();
    			ai.byteToDouble();
    			ai.findFrequency();
    		}
     
    		//ai.printFreqs();
    	}
    }


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Basic FFT to identify frequency

    Welcome to the forum
    The frequencies are off?
    Crystal ball says you might be right. However since we have no idea what they should be perhaps you should explain much more what you mean by "the frequencies are off".
    What output are you getting? What did you expect?

  3. #3
    Junior Member
    Join Date
    Aug 2013
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Basic FFT to identify frequency

    I can use a Piano or guitar to generate frequecies and use a tuner to check

  4. #4
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Basic FFT to identify frequency

    Please read: How to help yourself get help and try to explain your problem from the start.

Similar Threads

  1. FFT code
    By 15thknight in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 11th, 2013, 06:29 AM
  2. Replies: 1
    Last Post: September 9th, 2011, 07:21 AM
  3. How to identify a roman numeral
    By dunWorry in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 20th, 2010, 12:58 AM
  4. Identify and avoid some of the pitfalls in learning to use generics
    By JackyRock in forum Java Theory & Questions
    Replies: 0
    Last Post: February 6th, 2010, 05:12 AM