How to record sound with Java Sound?

I just want to record a clip of sound and save it to a WAV file. I exhausted the web but didn't find a tutorial. Would someone be kind enough to give me a tutorial or a sample code? The simpler the better. Thanks.

Here's the code I used to record and play sound. Hope the length do not confound you.
import javax.sound.sampled.*;
import java.io.*;
// The audio format you want to record/play
AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_SIGNED;
int sampleRate = 44100;
byte sampleSizeInBits = 16;
int channels = 2;
int frameSize = 4;
int frameRate = 44100;
boolean bigEndian = false;
int bytesPerSecond = frameSize * frameRate;
AudioFormat format = new AudioFormat(encoding, sampleRate, sampleSizeInBits, channels, frameSize, frameRate, bigEndian);
//TO RECORD:
//Get the line for recording
try {
  targetLine = AudioSystem.getTargetDataLine(format);
catch (LineUnavailableException e) {
  showMessage("Unable to get a recording line");
// The formula might be a bit hard :)
float timeQuantum = 0.1F;
int bufferQuantum = frameSize * (int)(frameRate * timeQuantum);
float maxTime = 10F;
int maxQuantums = (int)(maxTime / timeQuantum);
int bufferCapacity = bufferQuantum * maxQuantums;
byte[] buffer = new byte[bufferCapacity]; // the array to hold the recorded sound
int bufferLength = 0;
//The following has to repeated every time you record a new piece of sound
targetLine.open(format);
targetLine.start();
AudioInputStream in = new AudioInputStream(targetLine);
bufferLength = 0;
for (int i = 0; i < maxQuantums; i++) { //record up to bufferQuantum * maxQuantums bytes
  int len = in.read(buffer, bufferQuantum * i, bufferQuantum);
  if (len < bufferQuantum) break; // the recording may be interrupted
  bufferLength += len;
targetLine.stop();
targetLine.close();
//Save the recorded sound into a file
AudioInputStream stream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(buffer, 0, bufferLength));
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
File file = new File(...); // your file name
AudioSystem.write(stream, fileType, file);
//TO PLAY:
//Get the line for playing
try {
  sourceLine = AudioSystem.getSourceDataLine(format);
catch (LineUnavailableException e) {
  showMessage("Unable to get a playback line");
//The following has to repeated every time you play a new piece of sound
sourceLine.open(format);
sourceLine.start();
int quantums = bufferLength / bufferQuantum;
for (int i = 0; i < quantums; i++) {
  sourceLine.write(buffer, bufferQuantum * i, bufferQuantum);
sourceLine.drain(); //Drain the line to make sure all the sound you feed it is played
sourceLine.stop();
sourceLine.close();
//Or, if you want to play a file:
File audioFile = new File(...);//
AudioInputStream in = AudioSystem.getAudioInputStream(audioFile);
sourceDataLine.open(format);
sourceDataLine.start();
while(true) {
  if(in.read(buffer,0,bufferQuantum) == -1) break; // read a bit of sound from the file
  sourceDataLine.write(buffer,0,buffer.length); // and play it
sourceDataLine.drain();
sourceDataLine.stop();
sourceDataLine.close();You may also do this to record sound directly into a file:
targetLine.open(format);
targetLine.start();
AudioInputStream in = new AudioInputStream(targetLine);
AudioFileFormat.Type fileType = AudioFileFormat.Type.WAVE;
File file = new File(...); // your file name
new Thread() {public void run() {AudioSystem.write(stream, fileType, file);}}.start(); //Run this in a separate thread
//When you want to stop recording, run the following: (usually triggered by a button or sth)
targetLine.stop();
targetLine.close();Edited by: Maigo on Jun 26, 2008 7:44 AM

Similar Messages

  • Audio capture delayed with Java Sound and JWS

    Hi.
    I am experiencing quite a strange problem with Java Sound in my Java Web Start application. I am acquiring sound from the microphone through Java Sound, using a code which looks like this:
    ==============================
    AudioFormat audioFormat = new AudioFormat(11025, 8, 1, true, false);
    // Get a TargetDataLine from the appropriate mixer
    DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioFormat);
    TargetDataLine targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
    // Prepare the line for use
    targetDataLine.open(audioFormat);
    targetDataLine.start();
    targetDataLine.addLineListener(myLineListener);
    // Build an input stream from the line
    AudioInputStream audioInStream = new AudioInputStream(targetDataLine);
    // Create the output file
    File outputFile = new File("C:\\MySampleAudioFile.wav");
    // Start the actual audio file-writing operation
    AudioFileFormat.Type targetFileFormatType = AudioFileFormat.Type.WAVE;
    AudioSystem.write(audioInStream, targetFileFormatType, outputFile);
    ==============================
    This code is executed in an independent thread. As you can see from the code reported above, I add a LineListener to my TargetDataLine.
    The problem is that in my JWS application several seconds (about 5-6 seconds) elapse from the call to AudioSystem.write() and the reception of the START LineEvent on my LineListener. This delay only occurs when my JWS application is downloaded from my public internet website, while it is not present when I test my JWS application on my local LAN server.
    It looks like the call to AudioSystem.write() causes some kind of network connection to the remote web server of the JWS app, and this operation takes some time. In fact, if I download my JWS app to my client from the public web server, then I disable all network connections on my client, then the START event is received immediately after the call to AudioSystem.write()... This is STRANGE, isn't it???
    Do you believe the call to AudioSystem.write(), or any other Java Sound call, may cause a network connection to the server from which the JWS application has been downloaded?
    A final addition to the above picture: I also have a "Java Applet" version of this application, which is exactly identical to the JWS version and uses the same exact code to do audio acquisition from the microphone. But, in this case the delay is not present, even when running the applet from the public web server!
    Any help / suggestion would be highly appreciated.
    Best regards,
    Marco.

    Hi
    Just Visit the following link and download sample source code for rtp in java
    http://javasolution.blogspot.com/2007/04/rtp-using-java.html
    if u want know basic simple java voice chat then visit
    http://javasolution.blogspot.com/2007/04/voice-chat-using-java.html

  • How to implement effects in java sound

    I have read the programmer's guide in java sound and it said there that it can generate effects such as distortion, delay and others. I would like to implement some of those, I can already capture and play sound from a microphone but I don't know how to manipulate the data to get my desired effect. Can someone explain the content of the array of bytes? I also hope you can give me some hints or anything that could help me implement my own effect. Thanks in advance!

    going_infinity wrote:
    The contents of the double array do not exceed the range. They are mostly of -0.07 o 0.07.
    I forgot to post this code, this is how byte was transformed to a double array. I am just extending an existing codeAh, yes...that makes a lot more sense. I assumed you were reading from the line as double, and that wouldn't work. But you're already converting it, which is why everything stays in the range you'd expect.
    "Weirdness" solved.
    If I use the double array or the byte array, how can I implement some effects like echo or reverb? I understand that since the "raw data" provides amplitude, I can get it's frequency and there is some FFT involved. All I can see here is determining the pitch of the sound but still, no effects. I'm still confused on where to start. Well, it depends on the effect. I'm not an effects expert, so you'll probably want to go do some Google-ing for what all of the affects are...but I think I can explain an echo.
    Echo is a function of a variable, decay, which is how quickly an echo will fade away. From a physics perspective, think of decay as friction, it'll eventually stop a moving object.
    So, you might implement an echo kinda like the following
    for (int i = 0; i < buffer.length; i++) {
         double threshhold = 0.01;
         double decay = 0.5;
         double echo = sample;
         int j = i+1;
         while((Math.abs(echo) > threshhold) && (j < buffer.length)) {
              buffer[j++] += echo;
              echo *= decay;
    Where some decreasing-fraction of a sample is added to all samples in the future until it drops below some threshhold.
    That may or may not be an "echo" effect, necessarily, as I think that a "true" echo also has a peroid (the delay between the sound and its echo) that I'm not taking into effect, so that effect is probably more like overdrive...but it illistrates the point. You'll have to figure out what each effect "adds" or "subtracts" from the sound, and then loop-through the sound data sequentially adding the effects of the effect.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Only my rear speaker have sound with my sound blaster X-FI Xtreme Audio

    How do i set up my sound card to have full 5. surround sound with my Harman Kardon AVR. I plugged my optic cable in my sound card out to my AVR in, then only my rear speaker work. Please help me.

    when i used the test it show the sound i get on my rear speakers as front speaker sound on the image.

  • How to use connec with java 6.0 ?

    I often use the function below to connect Database:
         public Connection getConnection(){
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    conn=DriverManager.getConnection("jdbc:odbc:EmployeeManagerDB","sa","sa");
    System.out.println("Get connection successfully!");
    catch(Exception e){
                   System.out.println("Error: " +e);
    return conn;
    but now, with Java 6.0 . don't use "class.forName....for method"
    can you tell me how to use it??
    thanks !

    but now, with Java 6.0 . don't use
    "class.forName....for method" Where did you get this idea?He's perfectly correct. JDBC 4.0 takes advantage of the Java SE Service Provide mechanism in Java 6 to do away with the requirement. So, if you have Java 6 and a JDBC 4 driver (it's a mandatory feature) you simply omit the forName() call.
    The only problem is that there aren't that many complete JDBC 4 drivers out there yet.

  • How to use Entrust with java application on unix platform

    Hi all,
    i have question regarding the use of Entrust with java application on unix
    1)I want to use Entrust for encryption/decryption of the file in my core java application on unix platform.
    What should be requiremnet for the same and how it is implemented?.
    2) I want to Use Entrust for Authentication purpose in my java based web application on unix platform.
    What are requirements for Entrust Authentication and how it is implemented ?

    any one has solution?

  • Is it possible to see a film on appletv trough iPod  and ear sound with ear sounds with headphone of iPod?

    Is it possible to see a film on appletv trough iPod  and ear sound with headphone of iPod?

    No

  • How to record video with a watermark logo in Adobe AIR app?

    I would like to develop an app in Adobe AIR. The requirement is that video recording with a custom watermark logo on top left. Anyone have any idea, how to record a video with custom watermark?
    Please suggest some code or any reference, it would be helpful for all who is looking video recording.
    Thanks!

    Yeah I'm developing video recording ANE. It allows you to record the whole AIR stage, including anything you've got there (video, movieclips on top, Stage3D or whatever): http://rainbowcreatures.com/product_flashywrappers.php
    There's an online demo for Flash Player on the website,beven it's not as good as the AIR ones because Flash Player encoder is really slow by not being able to use native code or HW acceleration. But it shows the layering on top of video.
    If you want to make something like this yourself, you'd need to go the native extensions route.

  • How to realize them with Java Swing?

    1.I want to realize the function - Save, which is similar with "save" in windows notepad - after clicking "save", a dialog box is poped up, then i can input the filename and save it. Is there any ready class like JFileChooser in Java Swing?
    2.I want to set Font and color in the text area. I can do it now. But I must set the font and color b4 input the words. How can I do it like Windows Word - I just input my words, then I highlight them and select the font and colour....all highlighted words r change....can I don it with Java swing and how?
    Thanks..

    1.I want to realize the function - Save, which is
    similar with "save" in windows notepad - after
    clicking "save", a dialog box is poped up, then i can
    input the filename and save it. Is there any ready
    class like JFileChooser in Java Swing?JFileChooser is a Swing based dialog, use it for your problem.
    >
    2.I want to set Font and color in the text area. I can
    do it now. But I must set the font and color b4 input
    the words. How can I do it like Windows Word - I just
    input my words, then I highlight them and select the
    font and colour....all highlighted words r
    change....can I don it with Java swing and how?
    Thanks..I am currently working this, try the ElementIterator w/ the Document that your inputing, as you iterate throught the nodes, you modify the attribute sets there.
    Hope this helps.
    >

  • Do you know how to call RDF with java code?

    Say me a tip!
    Environment:
    Linux, Reports 6i,java beans, jsp
    My mission is to run a report with java code.
    But I don't know how to.
    Basic flow is :
    On web browser, call jsp a program and
    that jsp call a java module,
    and the java module call a reports RDF with parameters
    I don't need reponse message from rwcgi60 or rwrun60.

    hello,
    the easiest way is to use the regular HTTP request to either the servlet or the CGI to run a report request from within a java-class.
    regards,
    the oracle reports team --pw                                                                                                                                                                                                                                                                                                                                                                                       

  • Research - how to build OS with Java

    I intend to build the basic functionality of an OS with Java.
    Can anyone recommend a good book:
    - that explains the OS achitecture in depth.
    - gives a headstart to start programming OS concepts in Java

    you only need to know two things:
    - How to schedule threads
    - How to create a file system

  • How import policy file with Java Web Start

    hi everybody,
    I wrote an application launched by Java Web Start.
    This application encrypt data on the client side and POST them to the server.
    To encrypt I use JCE packages including sunjce_provider.jar, jce1_2_1.jar and
    local_policy.jar and US_export_policy.jar.
    local_policy.jar and US_export_policy.jar are not packages, each of them contains
    a policy file.
    When I test encryption on local no problem, but when I test with Java Web Start
    I've got this exception :
    java.lang.ExceptionInInitializerError:
    java.lang.SecurityException: Cannot set up certs for trusted CAs
    It's because the application launched by Java Web Start doesn't find local_policy.jar
    and US_export_policy.jar.
    There's a problem in my JNLP file :
    <jnlp spec="1.0+" href="http://myserver/sources/test.jnlp" codebase="http://myserver/sources">
         <information>
              <title>Java Web Start TEST</title>
              <vendor>NLE Intech</vendor>
              <description>cryptage then upload</description>
         </information>
         <security>
              <all-permissions/>
         </security>
         <resources>
              <j2se version="1.3" />
              <jar href="sunjce_provider.jar" />
              <jar href="jce1_2_1.jar" />
              <jar href="local_policy.jar" />
              <jar href="US_export_policy.jar" />
         </resources>
         <application-desc main-class="HelloWorldSwing" >
              <argument>c:\myfiletoencrypt</argument>
         </application-desc>
    </jnlp>
    thank you for your answer

    Hi Nicolas,
    If you migrate to JDK1.4 and use the signed Bouncy JAR, you could resolve the problem,
    if you don't want to use unlimited cryptography.
    See my posting on your other question.
    Agnes
    PS. There is a mistake in my other reply, the "local_policy.jar" and the other files must have
    to go into JRE/LIB/SECURITY directory

  • Recording audio with both sound card and mic

    how i can develop a program to record audio file from mic and sound card at the same time?? 
    Muhammad Shoaib Software Engineer Shamim & Co. (Pepsi Cola Bottlers) Multan, Pakistan +923136140304

    Here Recording Audio from a Microphone
    https://msdn.microsoft.com/en-us/library/ff827802.aspx
    chanmm
    chanmm

  • Using sound with Java

    Is there any way to generate sound from special files (ie , format that I created myself) instead of from supported files (ie, wave) ? i mean generate sound from RAW data. because I create sound from MATLAB and store it in my format and I want it to be playted using Java.
    Best Regards
    Theeraputh Mekathikom

    Is there any way to generate sound from special files
    (ie , format that I created myself) instead of from
    supported files (ie, wave) ? i mean generate sound
    from RAW data. because I create sound from MATLAB and
    store it in my format and I want it to be playted
    using Java.
    Best Regards
    Theeraputh MekathikomThe wave format is really simple. It's practically raw data (some metadata added). I think that probably it will be easier to create a wave file with matlab than working with a propritary format on Java. Just to some google search on waves.
    Hope this helps

  • Beehive recording plays with no sound even after downloading codec

    Hello - We recorded a session using beehive conference. This generated a .asf and .txt files.
    On windows 7, this refuses to play because of missing codec. We downloaded and installed codec as pointed out here https://forums.oracle.com/thread/2422267
    Now the .asf file opens and video is shown but there is no audio
    Note:- We also had a intercall going on for audio conference.
    Is there anything missing? Please help.

    Thanks pbell - but it did not work
    I installed this https://stbeehive.oracle.com/bcentral/action?page=downloadlanding&appId=Oracle+Beehive+Conferencing+Codecs|windows|all|desktop

Maybe you are looking for