Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa Java-Beginners Audio Level Meter

Have Programming Question? Ask it here!
 
 
 


xchris
Audio Level Meter
2 Answer(s)      4 months and 9 days ago
Posted in : Java Beginners


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

Advertisement
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
Audio
low CPU usage. There are slightly different ways of playing audio from an applet and from an application. Where to learn about Java audio A good way to learn about audio is to read the "Sound" section of the Java Tutorial (see Other
Advertisements
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
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
uploading audio file iphone
uploading audio file iphone  uploading audio file iphone
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
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
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
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
audio video conferencing
audio video conferencing  how to develop a chat application in peer to peer setup
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
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
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
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
HTML5 audio loop, Use of loop attribute of audio tag in  HTML5.
HTML5 audio loop, Use of loop attribute of audio tag in  HTML5. Introduction:Loop attribute is used for reputation of audio or music. It repeats audio file again, until you do not click any controls. It supports only Boolean
Remove Top-Level Container on Runtime
Remove Top-Level Container on Runtime  Remove Top-Level Container on Runtime
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
HTML5 audio autoplay, Use of autoplay attribute in audio tag.
HTML5 audio autoplay, Use of autoplay attribute in audio tag. Introduction:The autoplay is an audio tag attribute. It is only supported by HTML5. When it is present in audio tag, the music file will begin itself. or After loading
HTML5  audio tag example, Use of audio tag  in HTML5.
HTML5  audio tag example, Use of audio tag  in HTML5. Introduction:In this section, you will see the use and implementation of audio tag in HTML5. The <audio> tag is used to add audio in web page or HTML page. When
HTML5 audio autobuffer, Use of autobuffer attribute in audio tag.
HTML5 audio autobuffer, Use of autobuffer attribute in audio tag. Introduction:The autobuffer attribute has Boolean value. It is available in audio tag... in audio tag file; music will start buffering automatically . Declaration
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
how to add audio clip in swings with event handling
how to add audio clip in swings with event handling  hello dear, i wanna to play audio clip in java program in JFrame in swings by event handling ,it should be like when i click on a button , audio clip should play , plz tell me
HTML5 audio controls, Discuss the controls attribute of audio tag.
HTML5 audio controls, Discuss the controls attribute of audio tag. Introduction:The controls is attribute of audio. which is used for showing media player on browser. It supports only Boolean value. If it is present in audio tag
J2ME Audio Record
J2ME Audio Record       This example is used to record the audio sound  and play the recorded sound. In this example we are trying to capture the audio sound and encoded
Does javaScript have the concept level scope?
Does javaScript have the concept level scope?  Does javaScript have the concept level scope
Audio files,IDE - Design concepts & design patterns
Audio files,IDE  HI! Gurus.I am david.i am a new to Java.i need detailed explanation on how to Create Audio files using Java language.Also i need to know the things i can do with Netbeans 6.1 and JDK1.6.0. Can u also teach me
Audio MIDlet Example
Audio MIDlet Example       This example illustrates how to play audio songs in your... a player for an audio song by using of javax.microedition.media API. As you
Getting the Log Level of a Logger
Getting the Log Level of a Logger       This section helps you to learn about the getting log level... with the log level and the log message for the specific log record. And the last
how to start a java project from scratch level
how to start a java project from scratch level   1.how to start a java project from scratch level ?can u give me small example from design to development process
Isolation level using hibernate in DB2/As400 - Hibernate
Isolation level using hibernate in DB2/As400  I want to use isolation level 2 or higher using hibernate in DB2/AS400. I can't use journaling. If I use isolation level 0, then there is a problem of dirty-read which we can't afford
implementation of two level scheduler in cloud computing environment
implementation of two level scheduler in cloud computing environment  job submission in cloud computing
audio files in jdbc connectivity with ms-access - JDBC
audio files in jdbc connectivity with ms-access  i need to know how to retrieve audio files through jdbc connectivity with ms-access and how to play them through link in browser....  Hi Friend, Try the following code
What is Logging Level?
What is Logging Level?      ... the Object class. Java provides logging APIs like: Logger, Level, Handler etc... in descending order: SEVERE(Greater level) : This level shows log a SEVERE message
how to play audio track in java applat
how to play audio track in java applat  Sir,i took help of coding in how to play audio track in java applet....nd i found perfect code ..but when i run same code on net beans then it shows error that could not found main class
Play Audio in Java Applet
Play Audio in Java Applet      ... the sound file. This program will show you how to play a audio clip in your java applet... is used to play the sound while stop() method is used for stop the running audio
Create a Custom Log Level in Java
Create a Custom Log Level in Java       This section tells you how to create a custom log level... a custom log level in Java, is given as ahead. Descriptions of program
how to run audio files in net beans using j2me
how to run audio files in net beans using j2me  i am running the audioMidlet in net beans. Now where should i place the .wav files inorder to play them
Car Music Streaming via iPhone Bluetooth, iphone Bluetooth Audio Streaming
Stream iPhone Music in Car Using Bluetooth One of the nicest features Apple added in its iPhone 3.0 release is the ability to stream music from the iPhone to the Car audio using Bluetooth. If your car has a supported Bluetooth
What are the level in Jboss 5 application server to deploy the application
What are the level in Jboss 5 application server to deploy the application  What are the level in Jboss 5 application server to deploy... (allows an exception to encapsulate original lower-level exception) - Internet
data (image ,audio) inserting to data base (oracle 10g) and retriving the same data from jsp
data (image ,audio) inserting to data base (oracle 10g) and retriving the same data from jsp   data (image ,audio) inserting to data base (oracle 10g) and retriving the same data from jsp with script of data base plz help me
flex didn't know how to drag and drop video and audio in flip book - Framework
flex didn't know how to drag and drop video and audio in flip book  ... target to add the video audio and photo in this book i am able to add the photo in this book but i didn't able to add video and audio so pls help me for my project
Hi Every One , please give me some idia to opning audio File . please Help ..
Hi Every One , please give me some idia to opning audio File . please Help ..  hi Dear Friend , please give me a program to opening audio file that ech extention will except it ,play sound by Button (PLAY) , pause it by Pause
i want to create website,with manu with three level submenu on top side of page please send me code java
i want to create website,with manu with three level submenu on top side of page please send me code java   iam createing wibsite thats using eclipse andtomcat server,please help me to write menu with three level submenu
Top-level Listeners
Java Notes Top-level Listeners   This is an example of top-level Listeners in Java.   In this example you will learn how to create top level-listeners in swing applications.   Using this as a listener  
 

 

 

DMCA.com