473,402 Members | 2,046 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

Java - Audio Levels

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

Expand|Select|Wrap|Line Numbers
  1. public class Capture extends JFrame {
  2.  
  3.       protected boolean running;
  4.       ByteArrayOutputStream out;
  5.  
  6.       public Capture() {
  7.         super("Capture Sound Demo");
  8.         setDefaultCloseOperation(EXIT_ON_CLOSE);
  9.         Container content = getContentPane();
  10.  
  11.         final JButton capture = new JButton("Capture");
  12.         final JButton stop = new JButton("Stop");
  13.         final JButton play = new JButton("Play");
  14.  
  15.         capture.setEnabled(true);
  16.         stop.setEnabled(false);
  17.         play.setEnabled(false);
  18.  
  19.         ActionListener captureListener = 
  20.             new ActionListener() {
  21.           public void actionPerformed(ActionEvent e) {
  22.             capture.setEnabled(false);
  23.             stop.setEnabled(true);
  24.             play.setEnabled(false);
  25.             captureAudio();
  26.           }
  27.         };
  28.         capture.addActionListener(captureListener);
  29.         content.add(capture, BorderLayout.NORTH);
  30.  
  31.         ActionListener stopListener = 
  32.             new ActionListener() {
  33.           public void actionPerformed(ActionEvent e) {
  34.             capture.setEnabled(true);
  35.             stop.setEnabled(false);
  36.             play.setEnabled(true);
  37.             running = false;
  38.           }
  39.         };
  40.         stop.addActionListener(stopListener);
  41.         content.add(stop, BorderLayout.CENTER);
  42.  
  43.         ActionListener playListener = 
  44.             new ActionListener() {
  45.           public void actionPerformed(ActionEvent e) {
  46.             playAudio();
  47.           }
  48.         };
  49.         play.addActionListener(playListener);
  50.         content.add(play, BorderLayout.SOUTH);
  51.       }
  52.  
  53.       private void captureAudio() {
  54.         try {
  55.           final AudioFormat format = getFormat();
  56.           DataLine.Info info = new DataLine.Info(
  57.             TargetDataLine.class, format);
  58.           final TargetDataLine line = (TargetDataLine)
  59.             AudioSystem.getLine(info);
  60.           line.open(format);
  61.           line.start();
  62.  
  63.           Runnable runner = new Runnable() {
  64.             int bufferSize = (int)format.getSampleRate() 
  65.               * format.getFrameSize();
  66.             byte buffer[] = new byte[bufferSize];
  67.  
  68.             public void run() {
  69.               out = new ByteArrayOutputStream();
  70.               running = true;
  71.               try {
  72.                 while (running) {
  73.                   int count = 
  74.                     line.read(buffer, 0, buffer.length);
  75.                   if (count > 0) {
  76.                     out.write(buffer, 0, count);
  77.  
  78.                     System.out.println(line.getLevel());  // |-this is what i added-|
  79.                   }
  80.                 }
  81.                 out.close();
  82.               } catch (IOException e) {
  83.                 System.err.println("I/O problems: " + e);
  84.                 System.exit(-1);
  85.               }
  86.             }
  87.           };
  88.           Thread captureThread = new Thread(runner);
  89.           captureThread.start();
  90.         } catch (LineUnavailableException e) {
  91.           System.err.println("Line unavailable: " + e);
  92.           System.exit(-2);
  93.         }
  94.       }
  95.  
  96.       private void playAudio() {
  97.         try {
  98.           byte audio[] = out.toByteArray();
  99.           InputStream input = 
  100.             new ByteArrayInputStream(audio);
  101.           final AudioFormat format = getFormat();
  102.           final AudioInputStream ais = 
  103.             new AudioInputStream(input, format, 
  104.             audio.length / format.getFrameSize());
  105.           DataLine.Info info = new DataLine.Info(
  106.             SourceDataLine.class, format);
  107.           final SourceDataLine line = (SourceDataLine)
  108.             AudioSystem.getLine(info);
  109.           line.open(format);
  110.           line.start();
  111.  
  112.           Runnable runner = new Runnable() {
  113.             int bufferSize = (int) format.getSampleRate() 
  114.               * format.getFrameSize();
  115.             byte buffer[] = new byte[bufferSize];
  116.  
  117.             public void run() {
  118.               try {
  119.                 int count;
  120.                 while ((count = ais.read(
  121.                     buffer, 0, buffer.length)) != -1) {
  122.                   if (count > 0) {
  123.                     line.write(buffer, 0, count);
  124.                   }
  125.                 }
  126.  
  127.                 line.drain();
  128.                 line.close();
  129.  
  130.               } catch (IOException e) {
  131.                 System.err.println("I/O problems: " + e);
  132.                 System.exit(-3);
  133.               }
  134.             }
  135.           };
  136.           Thread playThread = new Thread(runner);
  137.           playThread.start();
  138.         } catch (LineUnavailableException e) {
  139.           System.err.println("Line unavailable: " + e);
  140.           System.exit(-4);
  141.         } 
  142.       }
  143.  
  144.       private AudioFormat getFormat() {
  145.         float sampleRate = 8000;
  146.         int sampleSizeInBits = 8;
  147.         int channels = 1;
  148.         boolean signed = true;
  149.         boolean bigEndian = true;
  150.         return new AudioFormat(sampleRate, 
  151.           sampleSizeInBits, channels, signed, bigEndian);
  152.       }
  153.  
  154.       @SuppressWarnings("deprecation")
  155.     public static void main(String args[]) {
  156.         JFrame frame = new Capture();
  157.         frame.pack();
  158.         frame.show();
  159.       }      
  160. }
Dec 9 '13 #1
5 1963
xchris
4
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 :

Expand|Select|Wrap|Line Numbers
  1. package soundRecording;
  2.  
  3. import java.io.File;
  4. import java.util.Formatter;
  5.  
  6.  
  7. public class Save {
  8.  
  9.     static Formatter y;
  10.  
  11.     public static void createFile() {
  12.  
  13.         Date thedate = new Date();
  14.         final String folder = thedate.curDate();
  15.         final String fileName = thedate.curTime();
  16.  
  17.     try {
  18.         String name = "Time_"+fileName+".csv";
  19.         y = new Formatter(name);
  20.         File nof = new File(name);
  21.         nof.createNewFile();
  22.         System.out.println("A new file was created.");
  23.     }
  24.     catch(Exception e) {
  25.         System.out.println("There was an error.");
  26.         }
  27.     }
  28.  
  29.     public void addValues(byte audio) {
  30.         Date d = new Date();
  31.         y.format("%s    " + "  %s%n",d.curTime(), audio);
  32.     }
  33.  
  34.     public void closeFile() {
  35.         y.close();
  36.     }
  37. }
Dec 17 '13 #2
chaarmann
785 Expert 512MB
If you use CSV, you need to separate the columns by comma.
Spaces are not working. if you have data that contains comma, then you also need to use quotation marks surrounding the columns. An example with 2 columns:
Expand|Select|Wrap|Line Numbers
  1. "This is, and it really is, column 1", "Spaces and     tabs do not disturb me"
By the way, why do you use "thedate" and not "theDate", "aDate", "myDate" or "ourDate"? You just started programming, so don't get used to bad habits. Simply name it "date".
And what is "nof"? Is it that what the fox says? No? Then why didn't you name it "batman" instead? Just kidding!
But please, no kidding, use meaningful names!
Dec 18 '13 #3
xchris
4
Thanks for your help and your example,I understood how to use it.

About the variable names,you are right about "thedate",I should name it "theDate".I didn't want to use just "date",because "Date" is the name of my class (I know that "date" and "Date" are different),but I wanted to make clear that this reffers to a specific day,so I named it "thedate".
"nof" stands for "name of file".Although "batman" would be cool,I'll propably use it in my next java project!
Dec 18 '13 #4
chaarmann
785 Expert 512MB
If you name a variable "date", because it is an instance of class Date, then that is a good thing. Every programmer then can easily remember what it is. Prefixes like "the" "a" "our" or "my" do not add anything to understand the meaning of the variable. They are just typing clutter and makes it longer and harder (explanation see below) to read. If you want to make clear that this variable refers to a specific day, then just name that day and what is so specific on it. For example you could name the variable "today", "yesterday", "christmasEve". In a more general form, you could name it "oldDate" if there also exists a "newDate". That means, if you use many dates, don't call them "date1", "date2" etc., but put the difference in a meaningful name, like "birthdayOfCat", "birthdayOfDog".

Explanation: Usually you know the name of a variable without reading all letters, you just read the first 2 letters (and maybe the last 2 letters and your brain already delivers the meaning) But it cannot do that if all your local variables start with "the" and ends with "String". Just test yourself: can you figure out the odd one out faster in the first or second line?

First line:
theframestring theframestring theframestring theframestring theframestring theframestring theframestring thegreenstring theframestring theframestring theframestring theframestring

Second line:
frame frame frame frame frame green frame frame frame frame frame frame frame frame

P.s: If your variable is only used temporary (for example a loop counter), that means within the surrounding 5 lines of code, then just give it a single letter.
Dec 19 '13 #5
xchris
4
Thanks,I'll try to do that on my future codes!
Dec 19 '13 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

25
by: wee | last post by:
I've been using Java for a few years now and am just amazed at how many new "technologies" or tools come out all the time (i.e., Struts, Java Server Faces, JMeter, jad, etc.). It is nigh impossible...
11
by: jim shirreffs | last post by:
Hello, I am trying to put together a Java system for playing audio CDs on a large CD player, I have most of it working But entering all the data like Artist, Title, track name, track length...
1
by: VB.NET | last post by:
I've seen tons of image galleries in java, but has anyone seen a fancy way of showcasing audio files?
2
by: Jobs | last post by:
Download the JAVA , .NET and SQL Server interview with answers Download the JAVA , .NET and SQL Server interview sheet and rate yourself. This will help you judge yourself are you really worth of...
1
by: mmc | last post by:
3 methods needs doing; wave1: This static method takes an AudioInputStream and gradually lowers and then raises the volume so that the new AudioInputStream appears to be constantly alerting in...
1
by: cyberbrain7 | last post by:
Please help me how to add audio application (not applet) using java. Thanks!!!
1
by: pankhudi | last post by:
Hi everyone... I have to do a project work related on online audio system in Java...I have done the server-client prog(socket prog) n playing audio files..But how to stream my audio file from one PC...
3
by: hzgt9b | last post by:
Using VS2005, VB.NET, I want to record audio from my sound card, or mic input... and while recording get feedback to create a sound meter for visual display. Due to budget constraints, I can't...
63
by: s0suk3 | last post by:
I've been programming Python for a couple of years now. Now I'm looking to move on to either C++ or Java, but I'm not sure which. Which one do you think will be a better transition for a Python...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.