Jump to content



Photo

Audio Level Meter

audio meter level sound java

  • Please log in to reply
14 replies to this topic

#1 xchris

xchris

    Neowinian

  • Joined: 10-December 13

Posted 10 December 2013 - 18:54

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 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!

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 +Majesticmerc

Majesticmerc

    Resident Idealist

  • Tech Issues Solved: 5
  • Joined: 24-August 05
  • Location: United Kingdom
  • OS: Arch Linux / Win 7
  • Phone: HTC One X

Posted 10 December 2013 - 21:06

I'm afraid I don't know Java at all, but looking at the documentation, -1 is the value of AudioSystem.NOT_SPECIFIED, so at a guess I'd say that 'line' is not pointing to a valid audio stream?



#3 +snaphat (Myles Landwehr)

snaphat (Myles Landwehr)

    Electrical & Computer Engineer

  • Tech Issues Solved: 29
  • Joined: 23-August 05
  • OS: Win/Lin/Bsd/Osx
  • Phone: dumb phone

Posted 11 December 2013 - 22:55

 Not implemented so it will always return -1: https://forums.oracl.../thread/1272831



#4 +Aheer.R.S.

Aheer.R.S.

    I cannot Teach Him, the Boy has no Patience!

  • Tech Issues Solved: 8
  • Joined: 15-October 10
  • Location: Wolverhampton, United Kingdom
  • OS: Windows 7 X64 Ultimate Edition
  • Phone: Sony Xperia Z1 Compact

Posted 11 December 2013 - 22:59

I'm afraid I cannot help you, but if you do get the applet w/e to work, would you upload some pics or video of it? Looks interesting to me and is gadgety enough for me to want to try it. :)

#5 +snaphat (Myles Landwehr)

snaphat (Myles Landwehr)

    Electrical & Computer Engineer

  • Tech Issues Solved: 29
  • Joined: 23-August 05
  • OS: Win/Lin/Bsd/Osx
  • Phone: dumb phone

Posted 11 December 2013 - 23:02

I'm afraid I cannot help you, but if you do get the applet w/e to work, would you upload some pics or video of it? Looks interesting to me and is gadgety enough for me to want to try it. :)

 

I think the applet DOES work, you just can't use TargetDataLine.getline() to grab the amplitude (have to implement yourself). It is from here if you wanted to take a look: http://www.java-tips...-sound-api.html :-)



#6 OP xchris

xchris

    Neowinian

  • Joined: 10-December 13

Posted 17 December 2013 - 13:51

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 :
 
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();
}
}

P.S. Aheer I'll upload the project once I fix this and it works properly  :)



#7 +snaphat (Myles Landwehr)

snaphat (Myles Landwehr)

    Electrical & Computer Engineer

  • Tech Issues Solved: 29
  • Joined: 23-August 05
  • OS: Win/Lin/Bsd/Osx
  • Phone: dumb phone

Posted 17 December 2013 - 16:34

Use commas as a delimiter not spaces. CSV = comma separated values 



#8 OP xchris

xchris

    Neowinian

  • Joined: 10-December 13

Posted 18 December 2013 - 11:38

Yeah,I didn't know that "\t" isn't working in csv.I changed the format to xls and it works now,thanks



#9 +snaphat (Myles Landwehr)

snaphat (Myles Landwehr)

    Electrical & Computer Engineer

  • Tech Issues Solved: 29
  • Joined: 23-August 05
  • OS: Win/Lin/Bsd/Osx
  • Phone: dumb phone

Posted 18 December 2013 - 16:27

Yeah,I didn't know that "\t" isn't working in csv.I changed the format to xls and it works now,thanks

 

xls is a binary format, not a textual format, so how is that working?  :o



#10 OP xchris

xchris

    Neowinian

  • Joined: 10-December 13

Posted 18 December 2013 - 17:39

Hmm,what do you mean?You can write text on xls  :busted:



#11 +snaphat (Myles Landwehr)

snaphat (Myles Landwehr)

    Electrical & Computer Engineer

  • Tech Issues Solved: 29
  • Joined: 23-August 05
  • OS: Win/Lin/Bsd/Osx
  • Phone: dumb phone

Posted 18 December 2013 - 20:24

Hmm,what do you mean?You can write text on xls  :busted:

 

See here:

http://superuser.com...v-and-xls-files\

 

What I'm saying is that you shouldn't be writing comma separated values in plain text with an extension of .xls -- The XLS format is not plaintext and isn't something you can view/write with a text editor. Create an XLS file with Excel and then try opening it with a text editor and you'll see what I mean.

 

Or here for the format: http://msdn.microsof...office.12).aspx



#12 OP xchris

xchris

    Neowinian

  • Joined: 10-December 13

Posted 19 December 2013 - 12:01

The code writes 480000 samples per minute,the maximum size of rows that excel loads is 1048576.The values are there,but it just can't load them.I can open it with word and I can see the values,although they are not in separated columns,just a tab between time and amplitude,but it's possible to separate them,by marking them and inserting a table.It's easy,but it takes time,cause of the amount of the values.



#13 +snaphat (Myles Landwehr)

snaphat (Myles Landwehr)

    Electrical & Computer Engineer

  • Tech Issues Solved: 29
  • Joined: 23-August 05
  • OS: Win/Lin/Bsd/Osx
  • Phone: dumb phone

Posted 19 December 2013 - 16:32

So you aren't using xls then...

 

A few things:

  • If you are trying to record the samples at 8Khz make sure that matches the sampling rate of the program (or more aptly double your sampling rate if you want to reconstruct the signal that is being recorded since you are essentially resampling it, see: http://en.wikipedia....i/Sampling_rate).
  • Don't use excel for this. It isn't the right tool for the job if you are trying to sample at these rates. Use gnuplot, matplotlib, matlab, etc.


#14 OP xchris

xchris

    Neowinian

  • Joined: 10-December 13

Posted 20 December 2013 - 10:55

Can I make it write the data on a matlab file?Or you mean I'll insert the xls file on matlab later?



#15 +snaphat (Myles Landwehr)

snaphat (Myles Landwehr)

    Electrical & Computer Engineer

  • Tech Issues Solved: 29
  • Joined: 23-August 05
  • OS: Win/Lin/Bsd/Osx
  • Phone: dumb phone

Posted 20 December 2013 - 20:42

Can I make it write the data on a matlab file?Or you mean I'll insert the xls file on matlab later?

 

You'd postprocess a csv file via matlab (or something else) to produce graphs. Excel isn't suited for these kind of datasets. 

 

http://www.mathworks...ef/csvread.html





Click here to login or here to register to remove this ad, it's free!