Results 1 to 9 of 9
Like Tree1Likes
  • 1 Post By masijade

Thread: Audio Level Meter

  1. #1
    xchris is offline Member
    Join Date
    Dec 2013
    Posts
    4
    Rep Power
    0

    Default Audio Level Meter

    Hello

    I'm new to programming and I'm trying to make a java application that will "hear" (not record necessarily) the sound and display how loud is.I'm thinking of converting the sound recordings to numbers,so I can see the difference on the sound levels.I got this code from here (java-tips) and I added the "getLevel()" method,which returns the amplitude of the current recording,but it's returning -1 everytime.I guess I'm not using it properly. Any ideas how I must call this method?I have to deliver my project in a week,so any help will be much appreciated!

    Java Code:
    public class Capture extends JFrame {
    
    	  protected boolean running;
    	  ByteArrayOutputStream out;
    
    	  public Capture() {
    	    super("Capture Sound Demo");
    	    setDefaultCloseOperation(EXIT_ON_CLOSE);
    	    Container content = getContentPane();
    
    	    final JButton capture = new JButton("Capture");
    	    final JButton stop = new JButton("Stop");
    	    final JButton play = new JButton("Play");
    
    	    capture.setEnabled(true);
    	    stop.setEnabled(false);
    	    play.setEnabled(false);
    
    	    ActionListener captureListener = 
    	        new ActionListener() {
    	      public void actionPerformed(ActionEvent e) {
    	        capture.setEnabled(false);
    	        stop.setEnabled(true);
    	        play.setEnabled(false);
    	        captureAudio();
    	      }
    	    };
    	    capture.addActionListener(captureListener);
    	    content.add(capture, BorderLayout.NORTH);
    
    	    ActionListener stopListener = 
    	        new ActionListener() {
    	      public void actionPerformed(ActionEvent e) {
    	        capture.setEnabled(true);
    	        stop.setEnabled(false);
    	        play.setEnabled(true);
    	        running = false;
    	      }
    	    };
    	    stop.addActionListener(stopListener);
    	    content.add(stop, BorderLayout.CENTER);
    
    	    ActionListener playListener = 
    	        new ActionListener() {
    	      public void actionPerformed(ActionEvent e) {
    	        playAudio();
    	      }
    	    };
    	    play.addActionListener(playListener);
    	    content.add(play, BorderLayout.SOUTH);
    	  }
    
    	  private void captureAudio() {
    	    try {
    	      final AudioFormat format = getFormat();
    	      DataLine.Info info = new DataLine.Info(
    	        TargetDataLine.class, format);
    	      final TargetDataLine line = (TargetDataLine)
    	        AudioSystem.getLine(info);
    	      line.open(format);
    	      line.start();
    	      
    	      Runnable runner = new Runnable() {
    	        int bufferSize = (int)format.getSampleRate() 
    	          * format.getFrameSize();
    	        byte buffer[] = new byte[bufferSize];
    	 
    	        public void run() {
    	          out = new ByteArrayOutputStream();
    	          running = true;
    	          try {
    	            while (running) {
    	              int count = 
    	                line.read(buffer, 0, buffer.length);
    	              if (count > 0) {
    	                out.write(buffer, 0, count);
    	               
    	                System.out.println(line.getLevel());  // |-this is what i added-|
    	              }
    	            }
    	            out.close();
    	          } catch (IOException e) {
    	            System.err.println("I/O problems: " + e);
    	            System.exit(-1);
    	          }
    	        }
    	      };
    	      Thread captureThread = new Thread(runner);
    	      captureThread.start();
    	    } catch (LineUnavailableException e) {
    	      System.err.println("Line unavailable: " + e);
    	      System.exit(-2);
    	    }
    	  }
    
    	  private void playAudio() {
    	    try {
    	      byte audio[] = out.toByteArray();
    	      InputStream input = 
    	        new ByteArrayInputStream(audio);
    	      final AudioFormat format = getFormat();
    	      final AudioInputStream ais = 
    	        new AudioInputStream(input, format, 
    	        audio.length / format.getFrameSize());
    	      DataLine.Info info = new DataLine.Info(
    	        SourceDataLine.class, format);
    	      final SourceDataLine line = (SourceDataLine)
    	        AudioSystem.getLine(info);
    	      line.open(format);
    	      line.start();
    	      
    	      Runnable runner = new Runnable() {
    	        int bufferSize = (int) format.getSampleRate() 
    	          * format.getFrameSize();
    	        byte buffer[] = new byte[bufferSize];
    	 
    	        public void run() {
    	          try {
    	            int count;
    	            while ((count = ais.read(
    	                buffer, 0, buffer.length)) != -1) {
    	              if (count > 0) {
    	                line.write(buffer, 0, count);
    	              }
    	            }
    	            
    	            line.drain();
    	            line.close();
    	            
    	          } catch (IOException e) {
    	            System.err.println("I/O problems: " + e);
    	            System.exit(-3);
    	          }
    	        }
    	      };
    	      Thread playThread = new Thread(runner);
    	      playThread.start();
    	    } catch (LineUnavailableException e) {
    	      System.err.println("Line unavailable: " + e);
    	      System.exit(-4);
    	    } 
    	  }
    
    	  private AudioFormat getFormat() {
    	    float sampleRate = 8000;
    	    int sampleSizeInBits = 8;
    	    int channels = 1;
    	    boolean signed = true;
    	    boolean bigEndian = true;
    	    return new AudioFormat(sampleRate, 
    	      sampleSizeInBits, channels, signed, bigEndian);
    	  }
    	  
    	  @SuppressWarnings("deprecation")
    	public static void main(String args[]) {
    	    JFrame frame = new Capture();
    	    frame.pack();
    	    frame.show();
    	  }	  
    }

  2. #2
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,848
    Rep Power
    5

    Default Re: Audio Level Meter

    Not that I know the answer, but this is a very complete source for information about the java sound API:

    Java Sound Resources

    You may be using the method correctly (I mean its not like you can call it in another way), but you have to understand that JavaSound is only an API - whatever methods it exposes do not necessarily have to be implemented by the actual implementation of that API. It may be that that method can only be used in certain circumstances, such as when playing a specific type of audio, or only when recording.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  3. #3
    xchris is offline Member
    Join Date
    Dec 2013
    Posts
    4
    Rep Power
    0

    Default Re: Audio Level Meter

    Thanks for your response gimbal!I think I found something there,but I have to try it first

  4. #4
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,848
    Rep Power
    5

    Default Re: Audio Level Meter

    Of course you do :)

    I can also advise you to look into Paul's Sound System, which in the area of Java game development is a bit of a standard to use. It provides access to audio implementations other than JavaSound, such as OpenAL. Perhaps it can also help you even when you don't want to make a game.

    3D Sound System
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  5. #5
    xchris is offline Member
    Join Date
    Dec 2013
    Posts
    4
    Rep Power
    0

    Default Re: Audio Level Meter

    Ok,I managed to make it capture audio and print on a xls file the timestamp and the value of the current sample,but there is a problem : even I've put some spaces between the time and the value and it seems that they are in different columns,they are actualy on the same column of the xls,it's just expanded and covers the next column (I can put a print screen if you don't understand).How can I make it print the data of time and amplitude in two different columns?Here's my code of the class which creates the file and saves the data on xls :

    Java Code:
    package soundRecording;
    
    import java.io.File;
    import java.util.Formatter;
    
    
    public class Save {
    	
    	static Formatter y;
    
    	public static void createFile() {
    	
    		Date thedate = new Date();
    		final String folder = thedate.curDate();
    		final String fileName = thedate.curTime();
    	
    	try {
    		String name = "Time_"+fileName+".csv";
    		y = new Formatter(name);
    		File nof = new File(name);
    		nof.createNewFile();
    		System.out.println("A new file was created.");
    	}
    	catch(Exception e) {
    		System.out.println("There was an error.");
    		}
    	}
    	
    	public void addValues(byte audio) {
    		Date d = new Date();
    		y.format("%s    " + "  %s%n",d.curTime(), audio);
    	}
    	
    	public void closeFile() {
    		y.close();
    	}
    }

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,931
    Rep Power
    19

    Default Re: Audio Level Meter

    The file you are creating is a CSV file (look at the extension).
    That's a Comma Separated Value file. You need to use commas, not spaces, to separate the values.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    xchris is offline Member
    Join Date
    Dec 2013
    Posts
    4
    Rep Power
    0

    Default Re: Audio Level Meter

    Yeah,I didn't know that,I used csv because my professor suggested that to me,I changed it to xls and used "\t" and now it's working,thanks

  8. #8
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default Re: Audio Level Meter

    Also posted here. Anyone answering may wish to check that they are not repeating anything already stated.
    gimbal2 likes this.

  9. #9
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,848
    Rep Power
    5

    Default Re: Audio Level Meter

    Quote Originally Posted by masijade View Post
    Also posted here. Anyone answering may wish to check that they are not repeating anything already stated.
    Stating up front the reason for posting a link to the cross-post to prevent confusion: a good practice, we should all do that.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Java Audio and Timer Functions, Audio Breaking
    By mjkaufer in forum AWT / Swing
    Replies: 1
    Last Post: 05-24-2013, 07:10 AM
  2. [SOLVED] Class-level vs Object-level method()
    By mfaizan24 in forum New To Java
    Replies: 7
    Last Post: 06-23-2009, 09:18 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •