Monday, November 16, 2009

Audio Capture Applet Source Code

Categories:

Hello friends,check for an fine program on java.....
Applet Class

/**
 *This is a simple Sound Recorder program written in java.
 *@author Tapas kumar jena
 *@mail tapas.friends@gmail.com
 */

import java.awt.FileDialog;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.BooleanControl;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Port;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.sound.sampled.AudioFormat.Encoding;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.Timer;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;


//Main class
public class AudioApplet extends JApplet implements ActionListener, ChangeListener, ItemListener {
 //Global declarations
 protected boolean running;
 ByteArrayOutputStream out = null;
 AudioFileFormat.Type fileType;
 Object lock = new Object();
 TargetDataLine line = null;
 SourceDataLine sline = null;
 volatile boolean paused = false;
 boolean first;

 JButton record;
 JButton play;
 JButton pause;
 JButton stop;
 JButton send;
 JButton listen;
 JButton save;

 JTextField fnametxt;
 JComboBox servercombo;
 JTextField statustxt;

 JSlider progress;
 JLabel time;
 Timer timer;
 int audioLength ;
 int audioPosition = 0;
 JLabel vol1 = null;
 JLabel vol2 = null;
 JSlider volslider = null;
 JToggleButton mute = null;
 FloatControl volCtrl = null;
 Port lineIn = null;
 String list[];
 volatile String msg;

 public void init()
 {
  setLayout(null);
  JLabel recorder = new JLabel("Recorder");
  JLabel fileName = new JLabel("Please Enter File Name");
  JLabel server = new JLabel("Listen From Server");
  JLabel status = new JLabel("Status...");

  fnametxt = new JTextField("FileName");
  servercombo = new JComboBox();
  statustxt = new JTextField("Check your status here...");

  record = new JButton("Record");
  play = new JButton("Play");
  pause = new JButton("Pause");
  stop = new JButton("Stop");
  send = new JButton("Upload");
  listen = new JButton("Listen");
  save = new JButton("Save");

  progress = new JSlider(0, audioLength, 0);
  time = new JLabel("0:00");
  mute = new JToggleButton("Mute");
  vol1 = new JLabel("Volume  -");
  vol2 = new JLabel("+");
  volslider = new JSlider(0,100);
  volslider.setToolTipText("Volume");
  volslider.setPaintTicks(true);
  volslider.setMinorTickSpacing(10);

  recorder.setBounds(10,10,70,25);
  record.setBounds(70,10,80,25);
  play.setBounds(155,10,80,25);
  pause.setBounds(240,10,80,25);
  stop.setBounds(325,10,80,25);
  fileName.setBounds(10,40,130,25);
  fnametxt.setBounds(180,40,140,25);
  send.setBounds(325,40,80,25);
  server.setBounds(10,70,130,25);
  servercombo.setBounds(180, 70, 140, 25);
  listen.setBounds(325,70,80,25);
  status.setBounds(10,100,70,25);
  statustxt.setBounds(100,100,222,25);
  save.setBounds(325,100,80,25);

  progress.setBounds(50, 140, 300, 20);
  time.setBounds(360, 140, 30, 20);
  vol1.setBounds(75, 170, 100, 20);
  volslider.setBounds(130, 180, 150, 20);
  vol2.setBounds(280, 172, 30, 20);
  mute.setBounds(330, 170, 65, 30);

  add(recorder);
  add(record);
  add(play);
  add(pause);
  add(stop);
  add(save);

  add(fileName);
  add(fnametxt);
  add(send);
  add(server);
  add(servercombo);
  add(listen);
  add(status);
  add(statustxt);

  add(progress);
  add(time);
  add(vol1);
  add(volslider);
  add(vol2);
  add(mute);

  record.setEnabled(true);
  pause.setEnabled(true);
  play.setEnabled(true);
  stop.setEnabled(true);
  save.setEnabled(true);
  send.setEnabled(true);
  listen.setEnabled(true);

  record.addActionListener(this);
  play.addActionListener(this);
  pause.addActionListener(this);
  stop.addActionListener(this);
  save.addActionListener(this);
  send.addActionListener(this);
  listen.addActionListener(this);
  mute.addActionListener(this);
  progress.addChangeListener(this);
  volslider.addChangeListener(this);
  servercombo.addItemListener(this);       
 }//End of init method

 //***************************************************/   
 //******* StateChanged method for ChangeListener*****/
 //***************************************************/

 public void stateChanged(ChangeEvent e) {
  if (e.getSource()==volslider) {
   volumeControl();
  }else {
   int value = progress.getValue();
   time.setText(value / 1000 + "." + (value % 1000) / 100);
  }
 }

 public void itemStateChanged(ItemEvent ie) {
  msg = "  Listening from server [buffering]...";
  statustxt.setText(msg);
  listenAudio();       
 }

 //***************************************************/   
 //***** ActionPerformed method for ActionListener****/
 //***************************************************/

 public void actionPerformed(ActionEvent e) {
  if(e.getSource()==record){
   msg = "  Capturing audio from mic.....";
   statustxt.setText(msg);
   record.setEnabled(false);
   pause.setEnabled(true);
   stop.setEnabled(true);
   play.setEnabled(false);
   save.setEnabled(true);
   if(paused)
   {
    resumeRecord();
   }       
   else
   {
    recordAudio();
   }
  }
  else if (e.getSource()==play) {
   msg = "  Playing recorded audio.....";
   statustxt.setText(msg);
   stop.setEnabled(true);
   if(first)
   {
    playAudio();
   }
   else
   {
    resumePlay();           
   }
  }
  else if (e.getSource()==pause) {
   msg = "Paused....";
   statustxt.setText(msg);
   record.setEnabled(true);
   pause.setEnabled(true);
   pauseAudio();
   first=false;
  }
  else if (e.getSource()==stop) {
   msg = "  Action stopped by user.....";
   statustxt.setText(msg);
   progress.setValue(0);
   record.setEnabled(true);
   stop.setEnabled(false);
   play.setEnabled(true);
   running = false;
   stopAudio();

  }
  else if (e.getSource()==save) {
   msg = "  Saving file to user's System....";
   statustxt.setText(msg);
   saveAudio();
  }
  else if (e.getSource()==send) {
   msg = "  Sending recorded file to server...";
   statustxt.setText(msg);
   uploadAudio();

  }
  else if(e.getSource()==listen){
   msg = "  Listening from server [buffering]...";
   statustxt.setText(msg);
   //code for listen audio   
  }
  else {
   muteControl();

  }
 }

 //******************************************/
 //**************   Method Declarations  ****/
 //******************************************/ 

 private void recordAudio() {
  first=true;
  try {
   final AudioFileFormat.Type fileType = AudioFileFormat.Type.AU;                      
   final AudioFormat format = getFormat();
   DataLine.Info info = new DataLine.Info(TargetDataLine.class, format);
   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);
       InputStream input = new ByteArrayInputStream(buffer);
       final AudioInputStream ais = new AudioInputStream(input, format, buffer.length /format.getFrameSize());
      }                           
     }
     out.close();
     }catch (IOException e) {                    
      System.exit(-1);
     }
    }
   };
   Thread recordThread = new Thread(runner);
   recordThread.start();
  }catch(LineUnavailableException e) {
   System.err.println("Line Unavailable:"+ e);
   e.printStackTrace();
   System.exit(-2);
  }
  catch (Exception e) {
   System.out.println("Direct Upload Error");
   e.printStackTrace();
  }
 }//End of RecordAudio method

 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);
   sline = (SourceDataLine)AudioSystem.getLine(info);
   sline.open(format);
   sline.start();              
   Float audioLen = (audio.length / format.getFrameSize()) * format.getFrameRate();

   Runnable runner = new Runnable() {
    int bufferSize = (int) format.getSampleRate() * format.getFrameSize();
    byte buffer[] = new byte[bufferSize];

    public void run() {
     try {
      int count;
      synchronized(lock){
       while((count = ais.read( buffer, 0, buffer.length)) != -1) {
        while(paused)  {
         if(sline.isRunning()) {
          sline.stop();
         }
         try{
          lock.wait();
         }
         catch(InterruptedException e) {
         }
        }
        if(!sline.isRunning()) {
         sline.start();
        }
        if(count > 0) {
         sline.write(buffer, 0, count);
        }           
       }                                             
      }
      first=true;
      sline.drain();
      sline.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.exit(-4);
  }
 }//End of PlayAudio method

 private void resumeRecord(){
  synchronized(lock) {
   paused = false;
   lock.notifyAll();
   first = true;
  }
 }//End of ResumeRecord method

 private void stopAudio() {
  if (sline != null) {
   sline.stop();
   sline.close();
  }else {
   line.stop();
   line.close();
  }
 }//End of StopAudio method

 private void resumePlay(){
  synchronized(lock) {
   paused = false;
   lock.notifyAll();
   System.out.println("inside resumeplay method");
  }
 }//End of ResumePlay method

 private void pauseAudio(){
  paused = true;
 }

 private void saveAudio() {
  Thread thread = new saveThread();
  thread.start();
 }

 private void uploadAudio() {
  Thread th= new uploadThread();
  th.start();
 }

 private void listenAudio() {
  Thread thread = new listenThread();
  thread.start();
 }

 private AudioFormat getFormat() {
  Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
  float sampleRate = 44100.0F;
  int sampleSizeInBits = 16;
  int channels = 2;
  int frameSize = 4;
  float frameRate = 44100.0F;
  boolean bigEndian = false;
  return new AudioFormat(encoding, sampleRate, sampleSizeInBits, channels, frameSize, frameRate, bigEndian);
 }//End of getAudioFormat method

 class saveThread extends Thread  {
  public void run(){
   AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
   FileDialog fd = new FileDialog(new Frame(), "Save as WAVE", FileDialog.SAVE);
   fd.setFile("*.wav");
   fd.setVisible(true);
   String name = fd.getDirectory() + fd.getFile();
   File file = new File(name);

   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());
    AudioSystem.write(ais,fileType,file);
   }catch (Exception e){
    e.printStackTrace();
   }
  }
 }//End of inner class saveThread

 class uploadThread extends Thread{
  public void run(){
   AudioFileFormat.Type fileType = AudioFileFormat.Type.AU;

   try{                   
    line.flush();
    line.close();
   }
   catch(Exception e){
    e.printStackTrace();
    System.err.println("Error during upload");
   }               
  }
 }//End of inner class uploadThread

 class listenThread extends Thread{
  public void run() {
   try {
    URL upload=new URL("http://localhost:8080/TapasApplet/upload");
    HttpURLConnection conn = (HttpURLConnection) upload.openConnection();
    conn.setRequestMethod("POST");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setDefaultUseCaches(false);
    conn.setChunkedStreamingMode(1000);
    conn.setRequestProperty("Content-Type", "application/octet-stream");
    InputStream is = conn.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String serfile = br.readLine();
    while(line != null){
     //un complete code here   
     serfile=br.readLine();
    }
   } catch (IOException e) {
    System.err.println("Error in UserThread run() method");
    e.printStackTrace();
   }
  }

 }

 public void volumeControl() {
  try {
   if(AudioSystem.isLineSupported(Port.Info.LINE_OUT))
   {
    lineIn = (Port)AudioSystem.getLine(Port.Info.LINE_OUT);
    lineIn.open();
   }
   else if(AudioSystem.isLineSupported(Port.Info.HEADPHONE))
   {
    lineIn = (Port)AudioSystem.getLine(Port.Info.HEADPHONE);
    lineIn.open();
   }
   else if(AudioSystem.isLineSupported(Port.Info.SPEAKER))
   {
    lineIn = (Port)AudioSystem.getLine(Port.Info.SPEAKER);
    lineIn.open();
   }
   else
   {
    System.out.println("Unable to get Output Port");
    return;
   }
   final FloatControl controlIn = (FloatControl)lineIn.getControl(FloatControl.Type.VOLUME);
   final float volume = 100 * (controlIn.getValue() / controlIn.getMaximum());
   System.out.println(volume);
   int sliderValue=volslider.getValue();
   controlIn.setValue((float)sliderValue / 100);

  } catch (Exception e) {
   System.out.println(" VOLUME control: exception = " + e);
  }
 }//End of volumeControl method

 public void muteControl() {
  BooleanControl mControl;
  try {
   mControl = (BooleanControl) sline.getControl(BooleanControl.Type.MUTE);

   if (mControl.getValue() == true)
   {
    mControl.setValue(false);
   }
   else
   {
    mControl.setValue(true);
   }             
  } catch (Exception e) {
   System.out.println(" MUTE control: exception = " + e);
  }
 }       
}//End of main class AudioBroadcast

The above prograam looks like below -




Spread The Love, Share Our Article

Related Posts

44 Response to Audio Capture Applet Source Code

Anonymous
February 3, 2010 at 6:08 PM

can you explain in detail how to set environment...
i have used this example, will it save the file automatically on the server if i press upload button on the applet.

Tapas@Admin
February 3, 2010 at 8:32 PM

You need to set the url for the servlet file on applet's Upload method. then it will store all the file to the the upload folder in server.
you just expain your requirement and you want more support contact me on tapas.friends@gmail.com.

May 25, 2010 at 9:11 AM

Why I run it fails. Can you explain the configuration to run it? Can use it to acquire embedded web and audio transmission between computers

July 31, 2010 at 1:50 PM

is it possible to capture audio output from speakers?

Ajith Mathew
September 18, 2010 at 7:43 AM

Hi..
I saved the file as AudioApplet.java
and the following error occurs
AudioApplet.java:415: cannot find symbol
symbol : class Encoding
location: class AudioApplet
Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
^

please help me

October 6, 2010 at 4:32 PM

Hello,
I am trying this code on Mac. Apple only starts with Mozilla (not with Safari) but record and play buttons don's seem to do anything... i haven't examined the code yet anyway ¿Anybody has put it to work using a mac browser?
thanks

February 7, 2011 at 11:40 PM

Hi All, You can find this application in Live at http://www.emuzix.net/capture.php

Hope it will help??

February 18, 2011 at 12:49 AM

Hey Guys, those who are facing compilation problem like

AudioApplet.java:415: cannot find symbol
symbol : class Encoding
location: class AudioApplet
Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
^
try the below solution:

Add the following import statement and ROCK.
import javax.sound.sampled.AudioFormat.Encoding;

February 18, 2011 at 7:39 PM

thanks for the source, it's working bro. thanks a lot

Anonymous
February 21, 2011 at 5:58 PM

sorry but when i run this source, the applet can't record my voice. is something wrong??
thank for the response

February 21, 2011 at 9:02 PM

There may be some problem in your hardware like mic or headphone. Otherwise it should work. Plz Check again and let me know?

Anonymous
February 23, 2011 at 6:13 PM

is this need the .php file for upload file ???

Anonymous
February 23, 2011 at 8:27 PM

sorry but i cant compile servlet class ???
package javax.servlet does not exist
what it this mean??? can you give me how to compile this source or maybe u can upload your full source with the compiled result

February 23, 2011 at 9:00 PM

No?PHP is not required as am already given the servlet class for uploading.You can use that.

m4
March 1, 2011 at 5:55 PM

i succes compile all files, but when i run, this rpogram can't record my voice. something wrong?

March 2, 2011 at 12:46 AM

Are you connected headphone or mic to the system??
if mic device is not connected then it will throw exception at run time.Check your Applet console and let me know the error message.

m4
March 3, 2011 at 5:36 PM

no error, i already try in my friend comp but still doesnt work. the timer for recording is stop

April 4, 2011 at 12:09 AM

can u upload the source which can run in localhost?? cause i try many time but the source doesnt work even has no error, i need this program for my final in my college. please send the source to my email.
thanks a lot
god bless u

April 20, 2011 at 11:20 PM

it's possible to run in apache web server ??? cause the source looks like need tomcat server

April 21, 2011 at 9:11 PM

No, web server in not required because i remove the uploading part from this program. If you want to upload your recorded file to server then you must require tomcat.

April 22, 2011 at 11:02 PM

i"m compile the program and running..
error "Direct Upload Error"

on line 333 "line.open(format);"

I use microphone, ever I have change value on this method. I still getting this error??

private AudioFormat getFormat() {
Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
float sampleRate = 44100.0F;
int sampleSizeInBits = 16;
int channels = 1;
int frameSize = 4;
float frameRate = 44100.0F;
boolean bigEndian = false;

return new AudioFormat(encoding, sampleRate, sampleSizeInBits, channels, frameSize, frameRate, bigEndian);

}//End

Anonymous
April 22, 2011 at 11:05 PM

could you send me a full source code on my email alexander.ok3@gmail.com?
because I'm still getting an error when I'm running It

Anonymous
April 23, 2011 at 7:42 AM

have u already test using web browser?? cause it can't upload to the server, even can't save the voice to the comp using save button. i tested using tomcat 7.

Anonymous
April 24, 2011 at 7:41 PM

can u explained this code??

URL upload=new URL("http://localhost:8080/TapasApplet/upload");
477
HttpURLConnection conn = (HttpURLConnection) upload.openConnection();
478
conn.setRequestMethod("POST");

because if u do direct upload why dont u use FileOutputStream() function

April 25, 2011 at 7:51 AM

Hi Alexander, I think you are using windows 7 Operating System. I found that the above exception is occurring only on windows 7 machine. In other machines it works fine. Upload will not work as i removed the respective code as it requires a java server to work.If you are facing problem in save, then check for applet security exception on console and let me know about the same.

For Anonymous
--------------
can u explained this code??

URL upload=new URL("http://localhost:8080/TapasApplet/upload");
477
HttpURLConnection conn = (HttpURLConnection) upload.openConnection();

These are the unnecessary codes. As Listen functionality is not implemented for now. You can leave those lines or you can write your own.

April 26, 2011 at 1:36 AM

im interest with your message to alexander, can u explain what you mean with security exception?? it's possible to run using tomcat 7 default securityor we must set manually?? thanks for the response.

April 26, 2011 at 4:29 AM

Hi yunus, security exception means if you are running the applet in a browser, it must have privileges to access the client's machine hardware resources. According to SUN the applet must be signed before running on a browser. You can check this link http://download.oracle.com/javase/tutorial/deployment/applet/security.html. I am not sure what exception it is throwing for Alexander but expecting security exception may be thrown.

Anonymous
April 26, 2011 at 8:52 PM

i running your code in browser but can't upload the voice, the status just stop in " Sending recorded file to server...". can u explain what's wrong with my comp?? i use tomcat 7, windows xp sp3. can i ask how to set privilege in xp ??
thanks a lot

rajeena
May 13, 2011 at 11:28 PM

Ur code looks great...
I tried ur code.It's working.but i cant upload.Is it required to save in local machine before uploading?i gave saved file name and I changed url and tried to upload to my server, but nothing gets uploaded.

Rajeena

May 14, 2011 at 2:04 AM

Hi Rajeena, its not required to save before upload. You can see my previous comments regarding upload to knom more regarding this.

November 12, 2011 at 2:01 AM

The applet run in Eclipse fine but when I run in browser than I can only see Applet but cant record file. Y SO ? Same problem occurred with http://www.emuzix.net/capture.php. Please reply.

November 12, 2011 at 5:26 AM

Check your Java Console. I guess it may thrown Security exception.

Anonymous
April 18, 2012 at 12:16 AM

Hi Tapas!!! Thanks a ton for this program. It's working fine. But when i record something and hear it, its not very loud. How do i increase the recording volume?

Anonymous
May 8, 2012 at 5:30 AM

hi Tapas

i also try your code. I actually need this code but i m facing the same problem button are visible to me but they are not recording. if i run it in appletviewer it works fine but not in browser. Sir plz tell me whats the issue..?????? i need it very much. response me on my emailid m12.verma@gmail.com

August 22, 2012 at 5:58 AM

i have done all work relate to project .and run smoothly but saved file voice is not work .

August 22, 2012 at 6:03 AM

cannot hear voice recorded

August 22, 2012 at 8:28 AM

Check your Mic and speakers. Is there any errors you found on console?

October 7, 2012 at 1:21 PM

hi friend , i sent a mail to you , my adress is galeriblue98@gmail.com . i need your software.
i use it here http://galeriblue.com/s.html but it does not work . please help

October 8, 2012 at 8:59 AM

What error you are getting in the java console?

January 6, 2013 at 5:16 PM

Hi Tapas-We are trying to run your code. It works OK if we run on without server. When we deploy and run it on server gives below exception:

Direct Upload Error
java.lang.IllegalArgumentException: No line matching interface TargetDataLine supporting format PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian is supported.


Would you please let us know: How can we fix this issue. It's very urgent waiting for your response.

Thanks!

February 5, 2013 at 2:12 AM

How do you deploy this code?

April 29, 2013 at 6:04 AM

Hie , i have copied ur code in the eclipse with the same class name but when i run the code the applet running ok with out any error but on click of record no progress, but when i click on save button wav file is created perfectly and running also out side. and no exception i m getting i am using
java version "1.6.0_29-ea"
Java(TM) SE Runtime Environment (build 1.6.0_29-ea-b08)
and windows 7(64 bit)

Also when i run the html file it displaying Error,click here for details in the browswer.
Can you please help me for solving the error.

April 29, 2013 at 6:16 AM

Check the error by using any debugger? It's hard to guess the error..

Anonymous
May 20, 2013 at 2:26 PM

The volume aint work well ,i mean it doesnt have much effect on the volume of the sound,can you tell me how to fix it or a way??

Post a Comment