Record while holding down a JButton - is that possible?

I'm gonna make a program that records while the user is pressing and holding down the Record button. Is that possible? How can I do it?
I have started with this code where I am using a mouseListener for the button and not an actionListener, that´s because I think a mouseListener is better if I want to implement a function that makes it possible to hold down the button while recording. Am I right? How can I write such a method?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import javax.sound.sampled.*;
class Recorder extends JFrame
     private JButton recordButt = new JButton("Record");
     private Socket sock = new Socket();
     private AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, false);
     private AudioFileFormat fileFormat = new AudioFileFormat(AudioFileFormat.Type.WAVE, audioFormat, 16);
     private AudioInputStream ais;
     private TargetDataLine tdl;
     private File file = new File("sound.wav");
     Recorder()
          super("Recorder");
          setLayout(new BorderLayout());
          JPanel north = new JPanel();
          add(north, BorderLayout.NORTH);
          north.add(recordButt);
          recordButt.addMouseListener(new RecordButt());
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          pack();
          setVisible(true);
     class RecordButt extends MouseAdapter
          Record r = new Record();
          public void mousePressed(MouseEvent e)
               r.start();
          public void mouseReleased(MouseEvent ee)
               r.interrupt();
     class Record extends Thread
          public void start()
               DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
               try
                    tdl = (TargetDataLine)AudioSystem.getLine(info);
                    tdl.open(audioFormat);
               catch(LineUnavailableException err) { System.out.println(err.getMessage()); }
               ais = new AudioInputStream(tdl);
               try
                     AudioSystem.write(ais, AudioFileFormat.Type.AU, file);
               catch(IOException e) {}
               tdl.stop();
               tdl.close();
     public static void main(String[] args)
          new Recorder();
}

Thanks!
I have modified the above code and I have marked the changes with the comment "marked" and now it looks like:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import javax.sound.sampled.*;
class Recorder extends JFrame
     private JButton recordButt = new JButton("Record");
     private Socket sock = new Socket();
     private AudioFormat audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, false);
     private AudioFileFormat fileFormat = new AudioFileFormat(AudioFileFormat.Type.WAVE, audioFormat, 16);
     private AudioInputStream ais;
     private TargetDataLine tdl;
     private File file = new File("sound.wav");
        boolean record = false;  // changed
     Recorder()
          super("Recorder");
          setLayout(new BorderLayout());
          JPanel north = new JPanel();
          add(north, BorderLayout.NORTH);
          north.add(recordButt);
          recordButt.addMouseListener(new RecordButt());
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          pack();
          setVisible(true);
     class RecordButt extends MouseAdapter
          Record r = new Record();
          public void mousePressed(MouseEvent e)
                      record = true;   // changed
               r.start();
          public void mouseReleased(MouseEvent ee)
               record = false;   // changed
     class Record extends Thread
          public void start()
               DataLine.Info info = new DataLine.Info(TargetDataLine.class, audioFormat);
               try
                    tdl = (TargetDataLine)AudioSystem.getLine(info);
                    tdl.open(audioFormat);
               catch(LineUnavailableException err) { System.out.println(err.getMessage()); }
               ais = new AudioInputStream(tdl);
               try
                              while(record)   // changed
                           AudioSystem.write(ais, AudioFileFormat.Type.AU, file);
               catch(IOException e) {}
               tdl.stop();
               tdl.close();
     public static void main(String[] args)
          new Recorder();
}But the Record button seems to hang while beeing pressed. Why?

Similar Messages

  • My macbook won't start up i have used the option command p r while holding down power button but not done.. please help guys

    my macbook won't start up i have used the option command p r while holding down power button but not done.. please help guys

    It not polite to repost asking fro more help three minutes after initial post.
    Recovery mode is Command & R keys after depressing and releasing the Power button  for a normal startup.
    OS X: About OS X Recovery - Apple Support
    That only works for Lion and later.
    What exactly happens when your try to boot to Recovery?
    Try starting in Safe Mode resetting the SMC and NVRAM/PRAM
    OS X: What is Safe Boot, Safe Mode?
    Intel-based Macs: Resetting the System Management Controller (SMC)
    About NVRAM and PRAM
    What model MacBook Pro and what OSX version was on the Mac?
    Have you tried booting from an OSX install DVD?
    When you try to start doe the Power light light?
    This is the Mac Pro desktop forum. I requested your post be moved to the MacBook Pro laptop forum.

  • My computer was rebuilt this week and I am in the process of setting up iTunes and have a weird setup issue. The music in my playlists plays but the same song doesn't play from the library. Initially, I opened ITunes while holding down Shift of control.

    My computer was rebuilt this week and I am in the process of setting up iTunes and have a weird setup issue. The music in my playlists plays but the same song doesn't play from the library. Initially, I opened ITunes while holding down Shift of control key.

    Scratch the post above - the musics that plays in the playlist also plays in the library and that is because i forgot that i imported from the cd yesterday. Basically, I see the rest of my music, but it doesnt' play and tells me it can't locate the file though the location in 'perferences' points to the correct location. Getting iTunes to play after a new computer or rebuild is a headache.

  • ITunes 11.0.4 still copying files to media library after dragging and dropping while holding down "option"

    I'm having trouble adding media without automatically copying the file to the iTunes media libary after dragging and dropping while holding down "option."
    In Preferences > Advanced, "Copy files to iTunes media folder when adding to library" is checked. When I drag a file into iTunes while holding "option", the green "plus" icon disappears. However, iTunes still copies the file to media folder.
    Any suggestions?

    you can also try:
    I found that if I SCROLL down to the word 'playlist' and hover around the name, a 'show' comes up.  Click on the 'show' and everything magically appears.

  • Trackpad "buttons" disabled while holding down key on keyboard

    Hello,
    ben having the following issue with the trackpad on this laptop:
    when playing games and holding down the W-key for example, the click functionality on the trackpad seems to be disabled. Neither tapping the trackpad nor clicking the lower left side works, untill i release the said keyboard key.
    the most usual issue, the entire trackpad beign disabled while typing is already "fixed" by turning the palm check off entirely. But dont seem to find option that enables the mouse button presses.

    @kekeplasteri ,
    Hello and thank you for posting on the HP support forums.  Here is a link you may find of use to help you with your touchpad issue.
    Using and Troubleshooting the TouchPad or ClickPad (Windows 8)
    Please let me know how things go.  
    Post back if you need any further assistance.
    Thank you again for posting and have a great day.
    Please click the "Thumbs Up" on the bottom right of this post to say thank you if you appreciate the support I provide!
    Also be sure to mark my post as “Accept as Solution" if you feel my post solved your issue, it will help others who face the same challenge find the same solution.
    D5GR
    I work on behalf of HP

  • Troubles with remote installation on older macbook- problem arises when I restart computer while holding down option key

    I've got remote disk sharing set up so I can upgrade my operating system from my desktop using snow leopard CD. My Macbook is able to read disk remotely and all goes well following directions for installation until I am supposed to hold down option key while restarting computer. When I do this, only my hard drive is an option for start up, not the hard drive and the disk as it shows in the instructions and pop up menu for start up. Why? What am I doing wrong with the start up? Also, it says I should be able to choose the Airport network, but my computer automatically connects and anyways, that is also not an option from the pop up menu (to choose a network and enter password), that pop up menu section doesn't show up at all, it goes right to choosing disc icon where only mac hard drive, not mac os x install, is an option. Does this make sense? I'm giving up for now.
    Thanks.

    The only known way to make it work on an external drive is by first installing Windows onto an internal drive, then cloning the install to an external Thunderbolt drive. Thunderbolt is seen as an extension of the internal bus, so Windows doesn't see it as an external device.

  • Vector images not sizing proportionally even holding while holding down shift.

    I use a Mac version 10.6.8 and Photoshop CS6.
    When I copy and paste a vector image from Illustrator, the vector image is not be sized at 100%x 100%. It comes in at weird sizes like 100% x 98.33% (this is not consistent, it changes numbers). I have to go into the top to manually change it to 100%x100% while in Transform mode.
    Also, after I change it to 100%x100% and try to scale by holding shift down, it will change again.
    I'm not sure what's happening. I've been using Photoshop for quite a few years so it's not a beginner problem.
    Does anyone know if there's an update to fix this problem or am I missing some setting somewhere?
    Thank you.

    Dr.
    Simple to see if using default settings (ie Snap vector Tools is checked)
    • create new file 400 x 400 px
    • draw out rectangle shape, about 150 x 75 px
    • go Edit>Transform Path>Scale
    • now hold down Shift key as you scale shape. Look at the Width and Height percentages in the option bar as you scale. You'll notice they vary from each other. Slightly. This is different behavior in CS6 than previous versions.
    It is more noticeable in a low res file. High res files will show less variation.

  • Rotating a scene while holding down the mouse?

    Hello Java Development community,
    I'm currently working on the beginnings of a 3D game that allows rotation, translation, and zooming of the scene/camera, but I've come across a problem that I can't solve. I want the scene to continually rotate when I press my mouse down on a side of the canvas and hold it there, but I'm not sure how to do that. I have a MouseListener that tells me where the user clicked/pressed and thus which way to rotate, but it will only rotate one unit per click. I want it to continually rotate at some rate while the mouse is held down. I don't know if this is possible, but any help would be much appreciated.
    Thanks,
    Jake

    Sorry, I wasn't that clear in the original post. I have a MouseListener and a MouseMotionListener. I have been able to record mousePressed and mouseDragged events, but mouseDragged events only fire when the mouse is held down and moved from the place where it was clicked. I want the scene to rotate while the mouse is held down and not moving. Maybe I'm missing something really basic or obvious here... I had tried making a silly loop in the mousePressed method that checks to see whether some boolean toggled by the mouseDragged method is true or not, but that doesn't seem to work because the program never leaves the loop to record other events that would change the loop condition...
    e.g. public class MyMouseListener implements MouseListener {
          public void mousePressed(MouseEvent e) {
                condition = true;
                while (condition) {
                     System.out.println("hi");
                     // rotate scene by x degrees
    public class MyMouseMotionListener implements MouseMotionListener {
          public void mouseDragged(MouseEvent e) {
                condition = false;
                System.out.println("bye");
    } Stupid, I know. But maybe it will help you see my problem.
    Message was edited by:
    jakeInJava

  • Getting message for every record while pressing down arrow key:apps form

    Hi,
    when i query the form and when I am going through the records by pressing the down arrow of the keyboard I am getting the message 'Do you want to Save the records' for every record even though i did not update any record
    How to avoid the message?
    I developed the form in oracle applications and it is a master detail form which have a header block and lines block.
    thanks & regards
    Deekshit

    Hello,
    You can review the following;
    https://metalink.oracle.com/metalink/plsql/f?p=200:27:627127677634310554::::p27_id,p27_show_header,p27_show_help:173383.995,1,1
    Hope it helps.
    Adith

  • Help! when i turn on my mac while holding down the option key to swith from windows to mac (i have just installed windows via bootcamp) it comes up with a white screen with a grey padlock asking for a password.

    I have not installed the windows drivers yet if that is relevant. here is a video of the problem https://www.youtube.com/watch?v=xR9dQPSIyNg

    Welcome to the Apple Support Communities
    That's the EFI password. If you don't know the password, the only thing you can do to turn it off is to take the Mac to an Apple Store.
    If you know the password, follow these steps to turn your EFI password off:
    1. Press Command and R keys while your Mac is starting to start into OS X Utilities.
    2. Go to Utilities menu > Firmware Password Utility, turn it off and restart your Mac

  • While holding down key on windows keyboatd, i am asked for a password but 11 months in storage i have forgotten Nny work arounds please

    My OS as beem upgraded to Panther

    Have you done a PRAM reset, CMD+Option+p+r...
    http://support.apple.com/kb/HT1379
    In fact, do 3 in a row, takes a bit of time.
    Try holding the Option or alt key at bootup?

  • HT201257 Hi -- I have a late 2011 13" macbook pro that shipped with and runs Lion. Unfortunately, I do not have the install disks with me. Holding down D key does nothing. What can I do?

    How can I run the hardware test on a macbook pro that SHIPPED with lion (never had an earlier OS) without access to the install disks? I am away from them and home for several months. Holding down the D key does nothing.

    Press "Option" and "D" key together.
    "Restart your computer, holding down the “D” key while the computer restarts.After your computer restarts, you should see the Apple Hardware Test chooser screen. If you don’t, Apple Hardware Test may not be available on your computer. You may be able to start Apple Hardware Test from the Internet. Reconnect your computer to the network, and then restart your computer while holding down both the Option and “D” keys."
    http://support.apple.com/kb/PH4510
    Best.

  • Macbook Pro is slow, freezes constantly and I'm forced to hold down the power button to turn it off.

    Hey all,
    This is my first post/discussion so hopefully I'm posting in the right section and all. Anyway, as of recently (few days) my Macbook Pro 15" (model previous to the one just released) has been been slow + lagging, also when this happens my computer freezes, but its kind of different: I can still move the cursor around and stuff, but for instance, if its google chrome that freezes I won't be able to close it, (tried force quit), after this, my whole computer kinda freezes and I can't close any of my programs, I can't click on the menu's at the top to shut down or doing anything really, eg. change internet connections. Closing my macbook, like shutting the lid doesn't solve anything, only turning it off by holding the power button for a few seconds, which I'm almost certain isn't a good thing. I've had to do this like 3 times today and its getting pretty frustrating.
    Something tells me that it might be because of memory usage, but I'm not entirely sure, I only say this because when looking at the available/free memory using iStat sometimes, its really low, like 12mb, 30mb, etc.
    Anyway, I know that's quite a lot of infomration but hopefully its useful, if there's any additional information you require that may be of help to you, please tell me and I'll do my best to provide it.
    Thanks,
    Roshen.

    Roshen,
    There are a couple of things you can try, but it sounds to me as if it's a problem with your hard drive.
    First, open Activity Monitor in your Utilities folder and see how much of your CPU % is being used by any one application (you can sort by %). If any one application/process is taking up more than 15% or so of your CPU, try killing (quitting) the process.
    Second, since yours is a 2011 model, it will have come with Lion installed. Shut down your machine and boot up while holding down the Command and R keys. Open Disk Utility and verify your disk. If it comes up with errors, click repair.
    If neither of these work, take your MBP into your local Apple Store. You should still be under warranty, even if you didn't purchase AppleCare. All beforehand and make an appointment.
    Good luck,
    Clinton

  • White Screen Of Death-Did all the key hold downs

    Hello,
    After the spinning beach ball of death today, the Imac is now in the White screen of death mode. I did power off, command option , p r keys with two chimes. I did the c key hold down. I tried the tech tool deluxe disc. I tried the power off only. I have unplugged and let it sit. Is there any thing else I can do?
    Thank You!

    Sorry, Kenichi, your post wasn't there a minute ago:(
    +did not work+
    Assuming you can get the Install Disc into the optical drive - with it already in the optical drive, then you power-up while holding down and continuing to hold down the c key (it's small case, so cap's lock off) until you see a spinning dial on the white screen (at that point you can release the c key) - how far does it get while trying to accomplish this?
    Does it do anything at all? Make any noise? Power light on or flashing? Do you ever get to hear the Mac startup "gong" sound? or see the spinning dial?
    The following article provides the startup sequence you might witness:
    http://support.apple.com/kb/HT2674?viewlocale=en_US
    http://support.apple.com/kb/HT2538?viewlocale=en_US
    Message was edited by: myhighway

  • My CD will not eject, tried holding down the trackpad and restarting still won't eject.

    My cd will not eject.  I tried restarting my Mac while holding down the trackpad, still it will not eject.  I hear it try to open but nothing happens.

    If you have a Retina model then you don't have a built in Superdrive, it would be external. As far as I know the holding down of the trackpad to Force Eject a CD/DVD disc from the drive only works on models that have built in CD/DVD drives. So you'll need to take ther drive apart to get the disc out.
    More than likely your external Superdrive has failed in some way, like the moter that is used to take in and eject the disc has failed.
    In the future buy a new DVD drive that is a tray load design. Any brand will work with your Mac. It does not have to have the Apple name on it to work properly on any Mac computer.

Maybe you are looking for