Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3613930
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T22:11:07+00:00 2026-05-18T22:11:07+00:00

I have a problem while recording the audio. I created a servlet and I

  • 0

I have a problem while recording the audio. I created a servlet and I modified the java sound API demo code to some extent and finally I can record the audio. The problem is that when I play the audio I can see the total time of the audio stored as 645.45 or something like that, but I have been recording the audio only for a couple of mins. One more problem is the audio is getting saved in the Eclipse directory instead of the project directory.

This is the servlet code.

package com;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;

public class SoundRecorder extends HttpServlet {

    private static final long serialVersionUID = 1L;

    static protected boolean running;
    static ByteArrayOutputStream out;
    double fileName = Math.random(); 
    //strFilename = nowLong.toString();



    public SoundRecorder() {
        System.out.println("Filename will be..." + fileName + ".wav");
    }

    public void init() {

    }

    public void destroy() {

    }


    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {  
        System.out.println("call received..");
        String method = request.getParameter("method");
        System.out.println(method);
        if("record".equalsIgnoreCase(method)) {
            captureAudio(true);
        }
        else if("stop".equalsIgnoreCase(method)) {
            captureAudio(false);    
        }
        else if("play".equalsIgnoreCase(method)) {
            System.out.println("yet to write");
            playAudio();
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {  
        System.out.println("call received..");
        String method = request.getParameter("method");
        System.out.println(method);
        doGet(request, response);
    }

    private void captureAudio(boolean capturing) {


            File outputFile = new File(fileName + ".wav");
            AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,44100.0F, 16, 2, 4, 44100.0F, false);

            DataLine.Info   info = new DataLine.Info(TargetDataLine.class, audioFormat);
            TargetDataLine  targetDataLine = null;

            try
            {
                targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
                targetDataLine.open(audioFormat);
            }
            catch (LineUnavailableException e)
            {
                System.out.println("unable to get a recording line");
                e.printStackTrace();
                System.exit(1);
            }

            AudioFileFormat.Type    targetType = AudioFileFormat.Type.WAVE;

            final Recorder recorder = new Recorder(targetDataLine,targetType,outputFile);

            System.out.println("Recording...");
            if(capturing){
            recorder.start();
            }
            else {
            recorder.stopRecording();
            }

    }



    private void playAudio() {
        try {
            File file = new File(fileName + ".wav");
            AudioInputStream stream  = AudioSystem.getAudioInputStream(file);
            AudioFormat format = stream.getFormat();
            DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat());
            Clip clip = (Clip) AudioSystem.getLine(info);
            clip.open(stream);              
            clip.start();
        } catch (Exception e) {
            System.err.println("Line unavailable: " + e);
            System.exit(-4);
        } 
    }
}

And this is the recorder class

public class Recorder extends Thread {
    private TargetDataLine  m_line;
    private AudioFileFormat.Type m_targetType;
    private AudioInputStream m_audioInputStream;
    private File m_outputFile;

    public Recorder(TargetDataLine line,
                     AudioFileFormat.Type targetType,
                     File file)
    {
        m_line = line;
        m_audioInputStream = new AudioInputStream(line);
        m_targetType = targetType;
        m_outputFile = file;
    }

    /** Starts the recording.
        To accomplish this, (i) the line is started and (ii) the
        thread is started.
    */
    public void start()
    {
        m_line.start();
        super.start();
    }

    /** Stops the recording.
    */
    public void stopRecording()
    {
        m_line.stop();
        m_line.close();
    }

    /** Main working method.
    */
    public void run()
    {
            try
            {
                AudioSystem.write(
                    m_audioInputStream,
                    m_targetType,
                    m_outputFile);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
    }

    private static void closeProgram()
    {
        System.out.println("Program closing.....");
        System.exit(1);
    }

    private static void out(String strMessage)
    {
        System.out.println(strMessage);
    }


}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T22:11:08+00:00Added an answer on May 18, 2026 at 10:11 pm

    When developing with servlets, you need to realize that there’s only one servlet instance throughout the whole webapp’s lifetime, from startup until shutdown. So, the HTTP requests from all visitors, all sessions, all browser windows/tabs, etc will all share the same servlet instance. Also, when you make a variable static, it will be shared among all instances of the same class (which is not really relevant here since there’s only one servlet instance anyway).

    In other words, those variables which you’ve declared in the servlet are not threadsafe:

    static protected boolean running;
    static ByteArrayOutputStream out;
    double fileName = Math.random(); 
    

    There’s only one of them and they are used by all visitors simultaneously. For the first two variables, which are continuously modified, this will lead to major threadsafety problems and for the third variable this means that all visitors record to the very same file. You need to declare them inside the doGet() block. You’d like to store the recording in the session by an unique request based token as key and then pass that key to the subsequent requests.


    As to the problem of the file being saved at the unexpected location; when you use relative paths in java.io.File in a servlet, then it will be relative to the directory from where the webserver is started. If you start it from inside Eclipse, then it’s saved in Eclipse directory. You’d like to use absolute path in java.io.File instead. If your intent is to save it in public webcontent (there where your JSP’s and the /WEB-INF folder is located), then you need ServletContext#getRealPath() to convert a web path to an absolute disk path.

    String relativeWebPath = "filename.ext";
    String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
    File file = new File(absoluteDiskPath);
    

    There’s however another problem with this: all files will get erased whenever you redeploy the webapp. If you want a bit more permanent storage, then you’d like to store it outside the web project. E.g. C:/path/to/recordings.

    File file = new File("C:/path/to/recordings/filename.ext");
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a problem while pasting my contents (or text) generated by Java code
I have problem while loading data into html select when users press or click
I have problem while using jquery maskedinput with asp.net textbox. I have a check
I have a problem while converting a string whose value is dd.mm.yyyy to DateTime
I have a problem while executing a SSIS script component. To be honest I
I have a problem while scrolling images on tableview. I am getting a Signal
i have a problem while loading a UITableView on UITabBarController, i got this error
I have a problem while publishing on the Market. My application does not use
I have very strange problem while I am submitting a practice problem on codechef.
I have a simple problem while putting text in multiple table! please have a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.