Clicking noise when streaming sound to SourceDataLine

Hello,
I'm trying to stream sound to the PC's speakers using SourceDataLine, but I have trouble getting rid of a clicking noise.
It seems to occur when sourceDataLine.available() equals sourceDataLine.getBufferSize(). Is there a way to avoid this?
I am dealing with an audio of indeterminate length. Here's the test code:
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class PlaybackLoop implements LineListener {
   SourceDataLine sourceDataLine;
   AudioFormat format;
   public PlaybackLoop() throws LineUnavailableException {
      AudioFormat.Encoding
          encoding = AudioFormat.Encoding.PCM_SIGNED;
      int sampleRate = 8000; // samples per sec
      int sampleSizeInBits = 16; // bits per sample
      int channels = 1;
      int frameSize = 2;  // bytes per frame
      int frameRate = 8000; // frames per sec
      // size of 1 sample * # of channels = size of 1 frame
      boolean bigEndian = true;
      format = new AudioFormat(
            encoding,
            sampleRate,
            sampleSizeInBits,
            channels,
            frameSize,
            frameRate,
            bigEndian);
      // PCM_SIGNED 8000.0 Hz, 16 bit, mono, 2 bytes/frame, big-endian
      DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
      sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
   public synchronized void play() throws LineUnavailableException,
                                          InterruptedException {
      int bytesPerSec = (int) format.getFrameRate() * format.getFrameSize();
      int intervalMs = 200;
      int loop = 50;
      int bytesSize = bytesPerSec * intervalMs / 1000;
      byte[] bytes = new byte[bytesSize];
      // creates a high pitched sound
      for (int i = 0; i < bytesSize / 2; i++) {
         if (i % 2 == 0) {
            writeFrame(bytes, i, 0x05dc);
         } else {
            writeFrame(bytes, i, 0x059c);
      sourceDataLine.open(format, 16000);
      sourceDataLine.addLineListener(this);
      int bufferSize = sourceDataLine.getBufferSize();
      System.out.println(format.toString());
      System.out.println(bufferSize + " bytes of line buffer.");
      long nextTime = System.currentTimeMillis() + intervalMs;
      sourceDataLine.start();
      for (int i = 0; i < loop; i ++) {
         int available = sourceDataLine.available();
         if (available == bufferSize) {
            // clicking noise occurs here
            System.out.println("*");
         int w = sourceDataLine.write(bytes, 0, bytesSize);
         long currentTime = System.currentTimeMillis();
         if (w != bytesSize) {
            System.out.println("Not all written.");
            // TODO
         // time adjustment , to prevent accumulated delay.
         long delta = (nextTime - currentTime);
         long wait = intervalMs + delta;
         if (0 < wait) {
            this.wait(wait);
            nextTime += intervalMs;
         } else {
            nextTime = currentTime + intervalMs;
      System.out.println();
      System.out.println("End play()");
   public static void main(String[] args) throws LineUnavailableException,
                                                 InterruptedException {
      new PlaybackLoop().play();
   public static void writeFrame(byte[] bytes, int halfwordOffset, int value) {
      writeFrame(bytes, 0, halfwordOffset, value);
   public static void writeFrame(byte[] bytes, int byteOffset,
                                 int halfwordOffset, int value) {
      byteOffset += 2 * halfwordOffset;
      bytes[byteOffset++] = (byte) (value >> 8);
      bytes[byteOffset++] = (byte) (value >> 0);
   public void update(LineEvent event) {
      System.out.println();
      System.out.print("Update:");
      System.out.println(event.getType().toString());
}

I have modified the code so that it shows how the audio goes out of synch
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
public class PlaybackLoop implements LineListener {
     SourceDataLine sourceDataLine;
     AudioFormat format;
     public PlaybackLoop() throws LineUnavailableException {
          AudioFormat.Encoding
                encoding = AudioFormat.Encoding.PCM_SIGNED;
          int sampleRate = 8000; // samples per sec
          int sampleSizeInBits = 16; // bits per sample
          int channels = 1;
          int frameSize = 2;  // bytes per frame
          int frameRate = 8000; // frames per sec
          // size of 1 sample * # of channels = size of 1 frame
          boolean bigEndian = true;
          format = new AudioFormat(
                    encoding,
                    sampleRate,
                    sampleSizeInBits,
                    channels,
                    frameSize,
                    frameRate,
                    bigEndian);
          // PCM_SIGNED 8000.0 Hz, 16 bit, mono, 2 bytes/frame, big-endian
          DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
          sourceDataLine = (SourceDataLine) AudioSystem.getLine(info);
     public synchronized void play() throws LineUnavailableException, InterruptedException {
          int bytesPerSec = (int) format.getFrameRate() * format.getFrameSize();
          int intervalMs = 200;
          int loop = 400;
          int bytesSize = bytesPerSec * intervalMs / 1000;
          byte[] bytes = new byte[bytesSize];
          // creates a high pitched sound
          for (int i = 0; i < bytesSize / 2; i++) {
               if (i % 2 == 0) {
                    writeFrame(bytes, i, 0x05dc);
               } else {
                    writeFrame(bytes, i, 0x059c);
          sourceDataLine.open(format, 16000);
          sourceDataLine.addLineListener(this);
          int bufferSize = sourceDataLine.getBufferSize();
          System.out.println(format.toString());
          System.out.println(bufferSize + " bytes of line buffer.");
          long nextTime = System.currentTimeMillis() + intervalMs;
          sourceDataLine.start();
          for (int i = 0; i < loop; i ++) {
               int available = sourceDataLine.available();
               if (available == bufferSize) {
                    // clicking noise occurs here
                    System.out.println("*");
               int w = sourceDataLine.write(bytes, 0, bytesSize);
               if (w != bytesSize) {
                    System.out.println("Not all written.");
                    // TODO
               // printing time drift
               if (i % 100 == 0) {
                    long currentTime = System.currentTimeMillis();
                    // this number increases
                    System.out.println(nextTime - currentTime);
               nextTime += intervalMs;
          System.out.println();
          System.out.println("End play()");
     public static void main(String[] args) throws LineUnavailableException, InterruptedException {
          new PlaybackLoop().play();
     public static void writeFrame(byte[] bytes, int halfwordOffset, int value) {
          writeFrame(bytes, 0, halfwordOffset, value);
     public static void writeFrame(byte[] bytes, int byteOffset,
                                         int halfwordOffset, int value) {
          byteOffset += 2 * halfwordOffset;
          bytes[byteOffset++] = (byte) (value >> 8);
          bytes[byteOffset++] = (byte) (value >> 0);
     public void update(LineEvent event) {
          System.out.println();
          System.out.print("Update:");
          System.out.println(event.getType().toString());
}The output looks like this:
PCM_SIGNED 8000.0 Hz, 16 bit, mono, 2 bytes/frame, big-endian
16000 bytes of line buffer.
Update:Start
200
1200
1450
1700
End play()
The printed number keeps on rising. (Maybe I'm not sending enough information to the audio input stream?)
The printed number should be stable if in synch, but it continues to rise, signifying that it's playing audio faster than it's being provided. When the audio input source is from a network streamed audio (instead of the test audio source in this example), it results in a buffer under run, which causes the clicking sound.

Similar Messages

  • I can't get my ipod classic (120GB) to work. I am getting error code 1434, and the ipod is making a lot of clicking noises when plugged in

    After coming back from Hawaii, my Ipod classic doesn't work anymore. When plugged into itunes, it says that it may be corrupt, and that I need to restore it. I have tried this, but everytime it gives me an error code of 1434. When I click more information, it sends me to a support page, but not for error code 1434. I tried all of the steps on the page hoping that it would help. Also my ipod is making  a lot of clicking noises when it is trying to run, alomst as if it is skipping inside and can't fully run. Can anyone help me ?

    Clicking sounds from an iPod that has a hard drive for storage is not a good thing.  It usually means the hard drive is faulty.  That is the likely reason for getting an error during the attempt to Restore.
    If you use a Mac, you can try putting the iPod into Disk Mode
    http://support.apple.com/kb/ht1363
    If it goes into Disk Mode, connect the iPod and instead of running iTunes, run Disk Utility.  Does the iPod appear in the Disk Utility sidebar?  If it does, select the iPod device in the sidebar, not the volume indented below the device (if there is one).  Go to the Erase tab.  Set the Format to Mac OS Extended (Journaled).  Name does not matter.  Click on Security Options and choose to write a single pass of zeros over the entire disk.  This serves as a good "stress test" for the iPod's hard drive.  Back on the main window, click Erase.
    This takes longer than a regular erase, but you should see steady progress.  If it errors out, or stalls for a LONG time (like hours), the hard drive is likely to be faulty.
    If it completes successfully, quit Disk Utility, run iTunes and try to do another Restore

  • Little clicking noise when computer picked up or moved.

    is it normal that my macbook pro 13 makes a little clicking noise when moved suddenly or picked up ? it sounds like the optical or hard drive to me.

    Hi nomadikpat,
    Your machine has an SMS (Sudden Motion Sensor) that is designed to park the drive head inside your hard drive when the machine receives a quick and sudden external force. This safety feature is designed to preserve the HD so that a mechanical failure doesn't potentially cause data loss.

  • Why does my MacBook Pro make clicking noises when pressure is applied to the unibody?

    I purchased a MacBook Pro in late July of this year. Recently, I have noticed that when I begin to type on the keyboard, the unibody will make a faint sound when pressure from my hands is applied to the MacBook. I also notice a faint clicking noise when I pick up the MacBook Pro to move it somewhere. Additionally, the screen hinge makes a faint clicking noise when the screen is opened. Are these sounds normal?

    Check if an AASP (Apple Authorised Service Provider) is closer, as some do not trust Geek Squad to diagnose something as simple as "all the keys are missing". But judge for yourself.: http://support.apple.com/kb/HT1434

  • My time capsule cannot connect to my system and I get an error msg -6753. I also get a clicking noise when I start up. I've tried every thing from re setting, un plugging and re setting but nothing works. Anybody have the same problem ?

    my time capsule cannot connect to my system and I get an error msg -6753. I also get a clicking noise when I start up. I've tried every thing from re setting, un plugging and re setting but nothing works. Anybody have the same problem ?

    A "clicking noise" is often a sign that a hard drive is malfunctioning. Suggest that you power down the device and take it to an Apple store to have them take a look, or contact Customer Service at Apple for instructions.

  • Ipod mini 2nd gen: clicking noise when plugged in only

    My mini just makes clicking noises when I plug it into the usb port. I thought it was the hard drive after reading tons of posts about the clicking noise, and got a compact flash replacement but it is still clicking. I dont think it is the battery. If it was, it should hold some sort of charge shouldnt it?
    What could be causing it?
    Is my mini out of whack? I did drop it before it died 2 years ago, but it worked for quite a few months after dropping it though. I just got around to working on it now cuz I miss it.

    thanks for the reply. well changing the hard drive was easy. it might be the battery. it did give me some errors before it crapped out. i just dont remember what those were. i think it was an apple with a lightning over it, which would indicate a bad battery i suppose. i will try to change the battery and see how that goes. i just cant troubleshoot since nothing comes on, except for a faint clicking noise when it's hooked up to the usb.

  • Clicking noise when playing rented movie on apple tv

    I am having trouble with my apple tv making a clicking noise when playing a rented movie from the iTunes store. Any suggestions?

    I get noise, krackering/clicking noise in left channel on rented movies, music/movies played through iTunes. NOT on Netflix. Only Apple content.
    Connected to a Samsung TV via HDMI.
    Very anoying.
    Any ideas?

  • My brand new mac book pro, which I've only turned on about 20 times since I purchased it, start making a loud constant clicking noise today -- it sounded like a combination of a computer notification tone and a weird druming sound.  What's the problem?

    my brand new mac book pro, which I've only turned on about 20 times since I purchased it, start making a loud constant clicking noise today -- it sounded like a combination of a computer notification tone and a weird druming sound.  What's the problem?
    Is this thing a piece of junk?  My MacBook Air is running fine.  I've literally only charged the MacBook Pro battery a handful of times -- it's brand new.

    At these prices don't screw around.  Just call applecare to arrange an appointment at the nearest apple store. 
    Alternatively post in the Macbook Pro forum.  This is the Mac Pro forum.

  • Small clicking noise when moving

    hello, ive only got the new macbook pro 13 the other day. when i slightly move the machine, it makes a small clicking noise (when its running with lid open), but it doesn't every time, like 3 out of 10 times. and i dont mean moving as in taking it into a different room, i mean like a slight move if i need to stretch or a wobble of my body with the macbook. any advice pls? thanks

    My 2.53ghz 13" macbook pro is doing the same thing. This is odd because the 13" unibody macbook I had before this also has SMS and it never did this. If it is the SMS sensor, it is kicking in for very slight movements.
    Could it be the SMS sensor is a little too sensitive? If so, is this something I should be concerned about?

  • Superdrive making clicking noise when my Macbook Pro is lifted

    Hello all,
    I recently had my New 13.3 in. Macbook Pro displayed replaced and now when I lift the Macbook, the superdrive makes a clicking noise similar to the sound when a dvd-rom can't read a disc. There is no dvd in the drive during this time. I was wondering if anyone else is experiencing this problem with their Macbook Pro.
    I have another question, when I received my macbook with the replaced display, the display had several patches of dirt and an line scratch underneath the screen. Will apple replace the screen for me again or is it possible to have the entire macbook replaced? This is very frustrating to have to send in my brand new macbook for repairs twice in one month...
    Thank you advance for your help.
    David

    DO NOT DOUBLE POST!
    I posted this link in your first question as well.
    http://discussions.apple.com/thread.jspa?threadID=2069071&tstart=0

  • Superdrive making clicking noise when Macbook is lifted

    Hello all,
    I recently had my New 13.3 in. Macbook Pro displayed replaced and now when I lift the Macbook, the superdrive makes a clicking noise similar to the sound when a dvd-rom can't read a disc. There is no dvd in the drive during this time. I was wondering if anyone else is experiencing this problem with their Macbook Pro.
    I have another question, when I received my macbook with the replaced display, the display had several patches of dirt and an line scratch underneath the screen. Will apple replace the screen for me again or is it possible to have the entire macbook replaced? This is very frustrating to have to send in my brand new macbook for repairs twice in one month...
    Thank you advance for your help.
    David

    http://discussions.apple.com/thread.jspa?threadID=2069071&tstart=0

  • Macbook pro 13in back case clicking noise when flexed? (late 2013)

    Yesterday I noticed that when I put a moderate (but by no means excessive) amount of pressure on the back of the case in certain areas with my thumb, there is a very audible clicking noise produced when the pressure is released. You can also feel resistance or a change in flex which to me, feels as though the case comes in contact with something on the inside of the computer, although I really can't be sure. It feels almost sticky when the pressure is released and the sound happens. What I'm wondering is, has anyone else experienced this, and if so was anything actually wrong, did it lead to issues etc. or is it just how the case sits. I looked at a display model of 13in late 2013 retina and it did not have this sound or feeling that I could tell (but still had similar flex). The 15 in late 2013 was much sturdier than the display 13 in retina and the old 13in without the retina screen felt like a solid piece of metal in comparison to my laptop. Here's a picture of the areas I can hear the sound when pressed
    It's not really the flex I'm concerned with, I am aware that flex happens when you have thin pieces of aluminum. This weird feeling and sound just don't seem normal to me. Please if you have a late 2013 13in retina, let me know if you hear or feel anything when you press here!

    Hi f,
    I know you're looking for someone with the same model MBP as you have; sorry, I don't have one, but I'd like to point out a couple of things.
    You already know that not all of them make that noise, as you've tested a display model. Because of that, I would definitely bring my MBP into an Apple Store and have them look at it. If you're still within 14 days of purchase, you may even want to consider a return and get a new one.
    Another point: if there is something amiss with your MBP, continuing to make it "click" could be causing harm, and I would stop doing it immediately, tempting as it may be. ;-)
    If the clicking is caused by picking up your MBP with one hand, use two hands to pick it up. As you've noticed, the case is rather "flexy;" this flex, exacerbated by picking it up with one hand, has caused internal hardware problems with MBPs and PBs in the past. If memory serves me, they used to put it in the owners manual; if they don't anymore, I think they should. Two hands.

  • Short Clicking noise when resuming pc after it has been idle

    This isn't really a problem just something that is annoying me. When going to my pc after it has been sitting idle, (not hibernating nor do I have the hardisks turnoff ever) I notice a one time short clicking noise from the box. To me it sounds like some extra voltage is being sent somewhere. It has never caused a problem and my rig is and has been stable since I built it. I did have a cheapo powersupply blow up on me so I've kinda been tuned in to that. Anyone know what I'm referring to? Thanks.

    It is a non issue really...I've had alot of machines do this...it is the HD that's doing it and some of them I've seen *especially the older drives* did it all the time...they have a spot that they rest the heads at and when you're away from the machine it parks it there...then it sets a safety level on it and when you come back it doesn't always wait for the safety lever to unegage and that is the click you hear...I don't know if they still do this or not but that click is common...
    Sometimes tho that click, to me, means that the drive is on its way out...but that hasn't been the norm...
    Cheers!! 8)

  • Clicking noise when playing MP3 tracks.

    This faint clicking noise started today in FCE 4.0.1 I have read some bits online about perhaps the CD's were old and that was the reason when I transferred the songs into MP3 to drag into my video clip. I have played the songs on iTunes and there is no clicking noise. Also I have music in my iTunes that I got off the internet and it works fine too in iTunes, but starts the clicking when in FCE.
    Also I have gone to other works I have created on FCE in the past and I have the same problems with the sound that I never use to have.
    Anyone have any ideas?

    FWIW, no version of FCP or FCE has ever worked natively with the MP3 audio format or even with AIFF audio at 44.1khz (CD Audio sampling rate). This has been well documented in the User's Manual since version 1.0. While you can import non-native audio, it will require rendering to play properly. But even with rendering, MP3 files can often exhibit clicking and other abnormalities.
    -DH

  • Why does my MacBook Pro make a clicking noise when i lift it up.

    Hi i just recently got a MacBook Pro. I get this weird clicking noise from the right side of the trackpad. I don't know why its doing this noise but i think its got something to do with the superdrive or cd drive. This only happens when i pick it up or rotate it around on my lap.

    Just to clarify... and in case you're not familiar with how hard drives work... There are metal platters in your hard drive that spin at either 5400 or 7200 times per minute (that's either 90 or 120 times per second respectively). There is a little read head that floats less than a papers width above that super fast spinning platter. If you bump your computer while the read/write head is over the platter, there is a chance it can bump into the spinning platter causing permanent damage to it. As a result, hardware manufacturers have developed ways to lock the head when a "sudden motion" is detected in order to reduce the chance of damage. In some cases (like the MacBooks), it is built into the notebook itself... in other cases, the technology is built into the drive. The clicking you hear, as others have indicated, is the sound of the drive head locking... it's a good thing.

Maybe you are looking for

  • Are we really vulnerable for plugins?

    Are we really vulnerable... or is the admonition to perform updates a catchall for out-of-date plugins? What I mean is, do these plugins really miss a new vulnerability every other week, or is the term "vulnerable" used to mean that there is a newer

  • First and last day of current year as a date object

    Howdy... can someone please help me out... i need a fast way to get the first day of the current year as a date object and the last day of the current year as a date object... big thanks for any sample code...

  • Cacutus testcase running error, please help me

    hi, i am working on cactus test case for the 1st time..i have tried with a sample application in cactus, it worked fine.. but when i m implementing the same thing in my application..it's giving me the following error in the client side.... org.apache

  • Label Printing Problem

    Hi I created a smartform( Travel Card in PP). the label is showing in Print Preview as   1                                                            2                                                            3 but the printouts are coming as  3   

  • Cannot open mailbox system attendand- randomly

    Hello, our environment have Exchange 2013 with CU7 installed, and lately receive weird problem that is not persistent but it unexplained. All databases mounted that are in DAG, all arbitration mailboxes good, in ADSIEDIT checked homeMDB, and it is no