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

December 17, 2013 at 7:26 PM

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

December 17, 2013 at 7:27 PM

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









Related Tutorials/Questions & Answers:
Audio Level Meter
Audio Level Meter  Hello I'm new to programming and I'm trying...); } } private void playAudio() { try { byte audio[] = out.toByteArray(); InputStream input = new ByteArrayInputStream(audio
ModuleNotFoundError: No module named 'progress_meter'
ModuleNotFoundError: No module named 'progress_meter'  Hi, My... named 'progress_meter' How to remove the ModuleNotFoundError: No module named 'progress_meter' error? Thanks   Hi, In your python
Advertisements
ModuleNotFoundError: No module named 'DR14-T.meter'
ModuleNotFoundError: No module named 'DR14-T.meter'  Hi, My Python... 'DR14-T.meter' How to remove the ModuleNotFoundError: No module named 'DR14-T.meter' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'flowdas-meter'
ModuleNotFoundError: No module named 'flowdas-meter'  Hi, My... 'flowdas-meter' How to remove the ModuleNotFoundError: No module named 'flowdas-meter' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'meter-reader'
ModuleNotFoundError: No module named 'meter-reader'  Hi, My Python... 'meter-reader' How to remove the ModuleNotFoundError: No module named 'meter-reader' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'Flask-Meter'
ModuleNotFoundError: No module named 'Flask-Meter'  Hi, My Python... 'Flask-Meter' How to remove the ModuleNotFoundError: No module named 'Flask-Meter' error? Thanks   Hi, In your python environment
ModuleNotFoundError: No module named 'insta-meter'
ModuleNotFoundError: No module named 'insta-meter'  Hi, My Python... 'insta-meter' How to remove the ModuleNotFoundError: No module named 'insta-meter' error? Thanks   Hi, In your python environment
ModuleNotFoundError: No module named 'plover-wpm-meter'
ModuleNotFoundError: No module named 'plover-wpm-meter'  Hi, My... named 'plover-wpm-meter' How to remove the ModuleNotFoundError: No module named 'plover-wpm-meter' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'rpi-power-meter-mqtt'
ModuleNotFoundError: No module named 'rpi-power-meter-mqtt'  Hi...: No module named 'rpi-power-meter-mqtt' How to remove the ModuleNotFoundError: No module named 'rpi-power-meter-mqtt' error? Thanks   Hi
ModuleNotFoundError: No module named 'ebot_meter_data_parser'
ModuleNotFoundError: No module named 'ebot_meter_data_parser'  Hi...: No module named 'ebot_meter_data_parser' How to remove the ModuleNotFoundError: No module named 'ebot_meter_data_parser' error? Thanks   Hi
Access level
Access level  Which access level allows exclusive access to the attributes and methods that belong to a class or classes derived from that class? default protected public private
Audio Processing
Audio Processing  Sir, I want implement an audio recognition system by using java.. Is it possible? and tell me the process... thank you
ModuleNotFoundError: No module named 'level'
ModuleNotFoundError: No module named 'level'  Hi, My Python program is throwing following error: ModuleNotFoundError: No module named 'level' How to remove the ModuleNotFoundError: No module named 'level'
ModuleNotFoundError: No module named 'level'
ModuleNotFoundError: No module named 'level'  Hi, My Python program is throwing following error: ModuleNotFoundError: No module named 'level' How to remove the ModuleNotFoundError: No module named 'level'
ModuleNotFoundError: No module named 'level'
ModuleNotFoundError: No module named 'level'  Hi, My Python program is throwing following error: ModuleNotFoundError: No module named 'level' How to remove the ModuleNotFoundError: No module named 'level'
Isolation level is used by the DBMS.
Isolation level is used by the DBMS.  What isolation level is used by the DBMS when inserting, updating and selecting rows from a database
Application Level Caching
Application Level Caching  How to create application level caching using mbean, without using any orm like hibernate
uploading audio file iphone
uploading audio file iphone  uploading audio file iphone
Second level cache
Second level cache  Hi, I have been asked one question which I have no idea about. It's like I have enabled second level caching and the data has... and how do I refresh( reload) my second level cache. Please advise, and ignore my
difference between first level and second level cache in hibernate
difference between first level and second level cache in hibernate  Difference between first level and second level cache in hibernate
difference between first level and second level cache in hibernate
difference between first level and second level cache in hibernate  Difference between first level and second level cache in hibernate
difference between first level and second level cache in hibernate
difference between first level and second level cache in hibernate  Difference between first level and second level cache in hibernate
difference between first level and second level cache in hibernate
difference between first level and second level cache in hibernate  Difference between first level and second level cache in hibernate
difference between first level and second level cache in hibernate
difference between first level and second level cache in hibernate  Difference between first level and second level cache in hibernate
Is Python a high level language?
Is Python a high level language?  Hi, I am beginner in Data Science...: Is Python a high level language? Try to provide me good examples or tutorials links so that I can learn the topic "Is Python a high level language?"
JAVA SYSTEM LEVEL PROGRAMMING
JAVA SYSTEM LEVEL PROGRAMMING  Hi we all know how to create a file in our system. if we want to create a text file we can do this in this way, RIGHT CLICK-NEW- TEXT DOCUMENT (in Windows 7). But, my question is how to get
converter code for audio file
converter code for audio file  how can i convert a audio file to a another file format like mp3
ffmpeg audio from video
ffmpeg audio from video  Hi, How to extract audio from a video file? Thanks
Remove Top-Level Container on Runtime
Remove Top-Level Container on Runtime  Remove Top-Level Container on Runtime
ModuleNotFoundError: No module named 'audio'
ModuleNotFoundError: No module named 'audio'  Hi, My Python program is throwing following error: ModuleNotFoundError: No module named 'audio' How to remove the ModuleNotFoundError: No module named 'audio'
audio file to play automatically
audio file to play automatically  I want to get an audio file to play automatically when someone visits my site
HTML audio tag
HTML audio tag  Hi, I have written a simple html page to play audio file, I m using audio tag as shown below: Your browser does not support the audio tag. when I open the page using Chrome, it works fine(plays audio
HTML5 audio reference
HTML5 audio reference  Hi, Tell me the best url to learn HTML5 audio tags with examples. Thanks   Hi, Learn how to use HTML5 audio tags to play the audio on web page. The HTML5 audio tag is used to play the video
ModuleNotFoundError: No module named 'pytest-level'
ModuleNotFoundError: No module named 'pytest-level'  Hi, My Python... 'pytest-level' How to remove the ModuleNotFoundError: No module named 'pytest-level' error? Thanks   Hi, In your python
Class level access
Class level access       Objective-C provides facility of class level access. In the examples given above we have used '-' sign before method, '-' means instance level
audio video conferencing
audio video conferencing  how to develop a chat application in peer to peer setup
received memory warning level 1
received memory warning level 1  received memory warning level 1 and if i continue to it .. i get second warning received memory warning level 2 And then my application get crash. Can any one please explain me what
Broadcasting audio.. - JSP-Servlet
Broadcasting audio..  i am doing a project on Internet radio. I embeded windows media player,but doesnt know how to broadcast...i need to stream the audio. can anyone give a solution for this. Its very urgent
how to stop audio (mp3)
how to stop audio (mp3)   if(e.getActionCommand(). equals("Stop")){ player.stop(); } i am making an audio player in which i have to stop a song. on writing player.close() it pauses the song rather than
playing an audio file
playing an audio file  In playing an audio file we have to take one method getAudioClip(getCodeBase(), "TestSnd.wav") inside that getCodeBase... how to solve this problem and also tell me where i should pass my audio clip
Java how to stop audio
{ AudioInputStream audio = AudioSystem.getAudioInputStream(new File...(audio); clip.start(); } catch...); } I want that when i press the stop button in the gui, the audio stops
data science entry level jobs
data science entry level jobs  Hi, I am beginner in Data Science... science entry level jobs Try to provide me good examples or tutorials links so that I can learn the topic "data science entry level jobs". Also tell me
data scientist entry level jobs
data scientist entry level jobs  Hi, I am beginner in Data Science... scientist entry level jobs Try to provide me good examples or tutorials links so that I can learn the topic "data scientist entry level jobs". Also
entry level jobs for data analyst
entry level jobs for data analyst  Hi, I am beginner in Data Science... level jobs for data analyst Try to provide me good examples or tutorials links so that I can learn the topic "entry level jobs for data analyst"
entry level jobs in data analytics
entry level jobs in data analytics  Hi, I am beginner in Data...: entry level jobs in data analytics Try to provide me good examples or tutorials links so that I can learn the topic "entry level jobs in data analytics"
entry level jobs data science
entry level jobs data science  Hi, I am beginner in Data Science... level jobs data science Try to provide me good examples or tutorials links so that I can learn the topic "entry level jobs data science". Also tell me
entry level jobs for data scientists
entry level jobs for data scientists  Hi, I am beginner in Data...: entry level jobs for data scientists Try to provide me good examples or tutorials links so that I can learn the topic "entry level jobs for data
entry level data science internships
entry level data science internships  Hi, I am beginner in Data...: entry level data science internships Try to provide me good examples or tutorials links so that I can learn the topic "entry level data science
entry level data scientist positions
entry level data scientist positions  Hi, I am beginner in Data...: entry level data scientist positions Try to provide me good examples or tutorials links so that I can learn the topic "entry level data scientist
deep learning entry level jobs
deep learning entry level jobs  Hi, I am beginner in Data Science... learning entry level jobs Try to provide me good examples or tutorials links so that I can learn the topic "deep learning entry level jobs". Also tell