Sound leak when using unsigned

I've generated a simple test case which should make this pretty straightforward. I'm using Linux Ubuntu 11.04 with pulseaudio, if it makes any difference.
Basically, I generate a very simple tonal sound for the musical note A3 using Java's java.sound.sampled APIs, and Clip to open and play it.
That's all well and good, but to avoid leaking sound resources, I have to listen to the Clip (or Line) for a STOP event, and then close it. That's fine too. If I play two sounds at the same time and do this, it works fine, too...
unless the sound encoding is unsigned. For some reason, switching it from signed to unsigned (and translating the tonal wave appropriately) makes me only able to close one of the Lines, and the other one goes rogue.
Here's my code:
http://pastebin.com/1mxBJ61t
or
import java.util.Timer;
import java.util.TimerTask;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineEvent.Type;
public class Test
     public static void main(String[] args)
          int volume = 64; //0-256
          double seconds = 2.0;
          double tone = 220.0; //Musical note A3 = 220.0
          final int sps = 80000; //sample rate (samples per second)
          final boolean signed = false;
          final byte[] toneData = makeTone(sps,tone,(int) (sps * seconds),volume,signed);
          //play the first tone
          try
               play(toneData,sps,signed);
          catch (Exception e)
               e.printStackTrace();
          //halfway through, play the second tone
          new Timer().schedule(new TimerTask()
                    @Override
                    public void run()
                         try
                              play(toneData,sps,signed);
                         catch (Exception e)
                              e.printStackTrace();
               },(long) (seconds * 500));
          //since the program doesn't know to terminate itself, we'll give it an explicit terminate
          new Timer().schedule(new TimerTask()
                    @Override
                    public void run()
                         System.out.println("Terminating");
                         System.exit(0);
               },(long) (seconds * 2000));
     //generates a simple tonal wave
     public static byte[] makeTone(int sps, double freq, int duration, int volume, boolean signed)
          byte[] r = new byte[duration];
          for (int x = 0; x < duration; x++)
               double wave = Math.sin((double) x / (sps / freq) * 2 * Math.PI);
               //taper off the end so it doesn't cut prematurely and 'blip'
               double taper = duration - x < 100 ? (duration - x) / 100. : 1;
               byte b = (byte) ((volume * wave * taper) + (signed ? 0 : 128));
               r[x] = b;
          return r;
     public static void play(byte[] data, int sps, boolean signed) throws Exception
          AudioFormat afmt = new AudioFormat(sps,8,1,signed,false);
          DataLine.Info info = new DataLine.Info(Clip.class,afmt);
          Clip c = (Clip) AudioSystem.getLine(info);
          c.open(afmt,data,0,data.length);
          c.start();
          //listen for the clip to stop, and then close it
          c.addLineListener(new LineListener()
                    @Override
                    public void update(LineEvent event)
                         System.out.println("Sound event: " + event.getType());
                         if (event.getType() == Type.STOP) event.getLine().close();
     }A few modifications you can make to see what I'm talking about:
Line 21, change signed to true, and everything works great.
Line 92, assuming signed is false, comment out this line, where I close the stream, and re-run. You will observe 2 Stop events. Enable it again and you will observe only 1 Stop event.
Am I doing something wrong, or is Java's sound system just that deplorable?
Thanks in advance,
-IsmAvatar

Thanks for replying again.
sabre150 wrote:
IsmAvatar wrote:
I dropped it down to 8000, but it still does the same thing for me. II didn't say it would - just that 80,000 seemed a very high sample rate. Unless you are playing sound to bats using hardware much better than I am then anything higher than a sample rate of 44 KHz is a waste of time. At my age the highest frequency I can hear is about 8 KHz so any sample rate much above 16 KHz is too high.
Makes sense.
have noticed varying behaviors.
I'm fairly new to this sound stuff, and at this point I'm just trying to get it to work. Get what to work? You have not really described, or a least I have not understood, exactly what you are trying to do. You have a clip of sound you are trying to play more than once but you are trying to "avoid leaking sound resources". Can you explain what you mean by this and why you think it necessary; a reference to some Java sound documentation would maybe help us understand.
Well, here's the sound documentation that I'm basing my code off of: http://download.oracle.com/javase/1.5.0/docs/guide/sound/programmer_guide/chapter4.html (and chapter 3)
Basically, my program has a play button that will play a sound that the user has loaded in (complex encodings or formats are not a concern currently). I need to be able to figure out how to handle the user clicking on the button multiple times. I would at least expect an average system to be able to play the sound twice concurrently (overlapping). Maybe I just have the wrong concept when I talk about "sound resources", but it seems like I run into problems down the road, like on my computer, after I've played the sound 30 times, it starts erroring, or if I try to play the sound twice, and then once more after they're done, it causes the application to hang. To me, this seems like it's looking for available lines, and just plum running out, or choosing a line it thinks is available, and hitting a wall. Idunno.
I have a .wav file that uses PCI Unsigned 8000 Hz that was exhibiting this problem. I don't think the '.wav' file was not exhibiting the problem I think your code is/was .
Fair enough. It's easier to fix the code then to expect to have certain types of wavs.
Ultimately it leads to the application hanging entirely,
I would be interested in seeing an SSCCE ( http://pscode.org/sscce.html ) that exhibits this since I have never met it.
I think it would be wise to deal with one problem at a time for now. The program that exhibits it is large and would be time-consuming to simplify. I figure the problems are interrelated, so if we can fix the current problem, the apparent freezing issue should resolve itself as well. If not, then I can make an SSCCE for that.
and I have to forcibly quit the JVM. Being able to close all sounds completely curtails that "feature", but it's apparently not an option for unsigned encodings.Since the difference between the two is just a toggle of one bit I don't really believe that this is a signed/unsigned problem. I believe there is something more fundamental to explain the problem. I expected as much. It's always nice to be able to fix one's own code/thinking than to hit a roadblock with the limitations of an API.
>>
Plus, your exception doesn't sound that desirable either.I didn't say it was desirable - I was just saying what I observed. My exception seems logical since the line I was trying to open was already open so a LineUnavailableException makes sense.I suppose so, yes. And I'm guessing your system is more than capable of playing two lines concurrently, if done correctly.
I suppose the problem that you're seeing (and probably mine, too) is that it's trying to recycle the Line (just a guess - I could be completely off). For whatever reason, mine lets me play the recycled line twice, but yours doesn't. Both ways cause issues.
I suppose this tells me that if I want to play another sound concurrently, I need another line, not a recycled one. Does that seem about right? If so, how might I go about doing that?
If not, perhaps I'm a little thick and need some hints.
In short, the problem is I would like to be able to play two sounds concurrently (seems like a reasonable enough request), but either I can't using my current code code (as you've seen), or it causes other issues (my side). So I'd like to know how to fix the code to enable this.
Greatly appreciated.
-IsmAvatar

Similar Messages

  • Poor sound quality when using air play

    How do I fix poor sound quality when using air play with my Denon receiver?

    I am not too sure if this is affected by BT software stack or RF design...
    iPhone 3G with FW 2.x provides Cisco VPN as well as Email support for corporate usage. However, it's weird that business man wouldn't want to use BT headset and talk to people... We are not asking about new feature support, like A2DP, but reliable, stable BT connection ONLY!!
    I've read that lots folks spent a lot of money on purchasing many different BT headsets and tried to get it work with iPhone 3G. I myself tried: Plantronics 510/815/855, Sony HBH-DS970/980, Nokia BH-903. None of them can work fine with my iPhone 3G ever! And iPhone 3G even cause BH-903 and DS-980 hang up after pairing or finishing call!!
    That's why I don't believe it's just a "SPECIAL CASE". How could a product FOR BUSINESS purpose get this kind of basic function problem?
    I hope we will find this issue could be resolved completely with new F/W, like Safari crash problem before. Other than this BT IOT problem, iPhone 3G is really the phone/companion could provide complete solution fulfill my personal and business needs.

  • Callers say my voice sounds muffled when using bluetooth.

    I have a motorola bluetooth h710/h715 and as soon as I got the iphone 4, everyone is telling my I sound muffled when using it, compared to my 3gs. Anyone else have this issue?

    Can a few of you help me with a test? I have a Jawbone 2 & a Jawbone Icon. Both exhibit a strange behavior with my iPhone 4. If either of these headsets are on, paired & connected AND a call is answered or initiated, things are fine.
    When it all goes downhill is in this scenario:
    My headset is OFF. I receive or make a call and mid-call, I decide to turn on the headset (which I keep off to save battery). The Jawbone connects and automatically switches the iPhone from PHONE to JAWBONE. This is all normal right? Okay here's the problem. The call quality has static, sounds muffled and the caller tells me I sound like I'm in a tin can. If I then switch back to the phone (through the iPhone page of Sources) and then back again, to the Jawbone, most times--quality is back to normal. Obviously this is not something we all want to be doing. Can anyone do this test with their headset .. any brand and even some of you with Icons? It would be good to know if the culprit is the Bluetooth Headset or the iPhone. Remember, it's important that you make a call with your Bluetooth headset in the OFF position and then turn it on mid-call to use it.

  • Siri sounds bad when using Bluetooth

    Siri sounds bad when using Bluetooth, but the phone calls sound great.

    Can a few of you help me with a test? I have a Jawbone 2 & a Jawbone Icon. Both exhibit a strange behavior with my iPhone 4. If either of these headsets are on, paired & connected AND a call is answered or initiated, things are fine.
    When it all goes downhill is in this scenario:
    My headset is OFF. I receive or make a call and mid-call, I decide to turn on the headset (which I keep off to save battery). The Jawbone connects and automatically switches the iPhone from PHONE to JAWBONE. This is all normal right? Okay here's the problem. The call quality has static, sounds muffled and the caller tells me I sound like I'm in a tin can. If I then switch back to the phone (through the iPhone page of Sources) and then back again, to the Jawbone, most times--quality is back to normal. Obviously this is not something we all want to be doing. Can anyone do this test with their headset .. any brand and even some of you with Icons? It would be good to know if the culprit is the Bluetooth Headset or the iPhone. Remember, it's important that you make a call with your Bluetooth headset in the OFF position and then turn it on mid-call to use it.

  • Sound distortion when using hdmi cable

    HP G62 notebook pc(Laptop) windows 7
    I have sound distortion when i connect laptop to pc using HDMI cable, happens after 10 minutes then sound is ok again then 10 minutes later sound distortion again. Sound on laptop is ok. Not HDMI cable because used other laptops and its works fine.

    I'm having this issue as well. Just posting to let people know there is more than one person with this issue. I have a pavilion dv5 laptop

  • Memory leak when "Use JSSE SSL" is enabled

    I'm investigating a memory leak that occurs in WebLogic 11g (10.3.3 and 10.3.5) when "Use JSSE SSL" is checked using the Sun/Oracle JVM and JCE/JSSE providers. The leak is reproducible just by hitting the WebLogic Admin Console login page repeatedly using SSL. Running the app server under JProfiler shows byte arrays (among other objects) leaking from the socket handling code. I thought it might be a general problem with the default JSSE provider, but Tomcat does not exhibit the problem.
    Anyone else seeing this?

    Yes, we are seeing it as well on Oracle 11g while running a GWT 2.1.1 application using GWT RPC. Our current fix is to remove the JSSE SSL configuration check, however this might not be an option if you really need it for your application. Have you found anything else about it?

  • Memory leak when using Threads?

    I did an experiment and noticed a memory leak when I was using threads.. Here's what I did.
    ======================================
    while( true )
         Scanner sc = new Scanner(System.in);
         String answer;
         System.out.print("Press Enter to continue...");
         answer = sc.next();
         new TestThread();
    ========================================
    And TestThead is the following
    ========================================
    import java.io.*;
    import java.net.*;
    public class TestThread extends Thread
    public TestThread() { start(); }
    public void run() {  }
    =====================================
    When I open windows Task Manager, every time a new thread starts and stops, the java.exe increases the Mem Usage.. Its a memory leak!? What is going on in this situation.. If I start a thread and the it stops, and then I start a new thread, why does it use more memory?
    -Brian

    MoveScanner sc = new
    Scanner(System.in);out of the
    loop.Scanner sc = new Scanner(System.in);
    while (true) {
    That won't matter in any meaningful way.
    Every loop iteration creates a new Scanner, but it also makes a Scanner eligible for GC, so the net memory requirement of the program is constant.
    Now, of course, it's possible that the VM won't bother GCing until 64 MB worth of Scanners have been created, but we don't care about that. If we're allowing the GC 64 MB, then we don't care how it uses it or when it cleans it up.

  • SOund problem when using Wi-fi

    I have problems with the audio when using wifi...  electric disturbance like sound(hiccups) when hearing songs or watching videos...
    when wifi is turned off no problems....
    whats the solution for this ?   can installing any driver solve the problem?
    just purchased the lap .... please reply fast

    Seems to me like a case of a dying headphone jack.
    Try playing with the jack (not the iPhone) while playing music, see if it actually causes the "in-out" thing.
    If it did, and you are still under warranty, take it to Apple and they'll hopefully give you a replacement.
    I put the iPhone in my pocket, and so far I have killed 3 iPhone headphones and 2 Shure ones this way. I moved to much more expensive Shure's as I thought they would be harder to break and while they lasted longer, they still died.
    I'd recommend avoiding pressure on jack as much as possible.

  • Microphone sounds low when using face time

    For some reason people complain when i use my microphone on my display when using Face Time
    that the voice is very low any suggestions.
    When i record on quick time it is fine you think its a face time issue ?

    Skype I mean.

  • No sound when on Facebook app. Sound ok when using I pad otherwise

    How can I get the audio to work when using Facebook app?  The audio is ok when using the iPad otherwise.  I already tried to fix by deleting the app and reinstalling also tried to reboot.  No luck. Please help.  I had been using Facebook previously without any problem.

    Hi,
    Try a clean installation of the flash plugin/activeX as follows.
    First, download the Flash uninstall utility on the link below and save it to your Downloads folder.
    Flash Player Uninstaller.
    When the download has completed, close all browser windows, open your Download folder and run the uninstaller.  After this has completed, restart the notebook.
    When windows has reloaded, download and install the latest version of Adobe Flash.  Note: You may want to deselect the option to include McAfee Security Scan Plus before downloading.
    When the installation has completed, restart the notebook again nefore checking if you now have audio on the internet.
    Regards,
    DP-K
    ****Click the White thumb to say thanks****
    ****Please mark Accept As Solution if it solves your problem****
    ****I don't work for HP****
    Microsoft MVP - Windows Experience

  • 2 Apple TV's and no sound output when using AirPlay/mirroring?

    Hi,
    Bought my first apple tv and when air mirroring was able to go to my system preferences and choose sound output for it and it worked beautifully when I wanted to play a movie on my computer and send it to the TV.  Bought a second apple tv for the bedroom, both are connected over wifi.  Using Mountain Lion on my iMac.  Now it won't play any sound on either and will not let me choose which apple tv in system preferences - sound.  Any help would be appreciated
    Sue
    I have tried turning Apple TV on first, then choosing sound output before turning on air mirroring.  Problem is it won't let me choose, stays on internal speakers.
    This fix won't work for me.

    Might I recommend the following sample code instead?
    [http://www.jsresources.org/examples/MidiNote.html]

  • Having 2 level of sound volume when using internal speakers or headset

    Hello to everyone.
    I have a HP Probook 4530s which I bought september 2011. I have never had any hardware difficuallty with my system and I'm very happy with it.
    Yesterday, I updated a few of my laptop drivers sush as LAN, Pointing Devices, HP Power Assistant and finaly sound card driver which is an IDT High Definition Audio CODEC all recomended by HP support Assistant Program.
    I tried to test the functionallity of my system after downloading and installing these new updates to see if any of them have any problem. That's when I noticed that my sound experience have been altered. Previously when I was using my system with a pair of headphones and my sound level was for example 70% and when I disconnect the headphones the sound level would suddenly jump to the value that I was using last time without headphones for example 25%.
    As of yesterday after updating the drivers, I can't have that feature.
    Please HELP, and thanks in advanced.

    Hi Shahramb,
    Your ProBook 4530s is a commercial product and to get your issue more exposure I would suggest posting in the commercial forums. Here is a link to the Commercial Notebook forum.
    Thank you,
    Please click “Accept as Solution ” if you feel my post solved your issue.
    Click the “Kudos Thumbs Up" on the right to say “Thanks” for helping!
    Thank you,
    BHK6
    I work on behalf of HP

  • Memory leak when using DB_DBT_MALLOC in CDB.

    Hello!
    Recently when I'm using Berkeley DB CDB and set the value Dbt DB_DBT_MALLOC, I noticed that the app's memory keeps growing during the db.get while;
    I found that many codes on the internet use the syntax free(value.get_data()), but when I tried to free the value.get_data(), I always got an interruption error.
    It's OK when I'm using the DB_DBT_USERMEM flag. So I just get very confused about the DB_DBT_MALLOC and DB_DBT_REALLOC.
    And also, I wonder why there's no memory leak problem when we use the single thread BDB. I think BDB cannot free the value.data pointer too in single thread before the app finish using it, then why our apps don't need to free the data afterwards?
    Thanks a lot in advance!

    You should use free() to free the DBT memory allocated via DB_DBT_MALLOC. You should do that after each Db::get() operation (and of course after finishing processing/using the data), otherwise you will loose the pointer to the memory previously allocated if you happen to reuse the DBT with DB_DBT_MALLOC (the data field will point to a new memory address).
    Alternatively you could use DB_DBT_REALLOC or DB_DBT_USERMEM.
    Note that there are small structures that BDB creates in the environment regions that only get freed/cleaned when the environment is closed.
    If you suspect that there is a memory leak inside the BDB code, make sure you rebuild Berkeley DB using the following configuration options (along with the others you use) when building: enable-debug, enable-umrw. Than, run the program under a memory leak detection utility, like Valgrind (allow the application to open and close the BDB environment) and see if there are any leaks reported.
    If memory leaks are reported, then put together a small stand-alone test case program that demonstrates the leaks, and post it here.
    Regards,
    Andrei

  • Memory leak when using database connectivity toolset and ODBC driver for MySQL

    The "DB Tools Close Connection VI" does not free all the memory used when "DB Tools Open Connection VI" connects to "MySQL ODBC Driver 3.51".
    I have made a small program that only opens and close the connection that I run continously and it's slowly eating all my memory. No error is given from any of the VI's. (I'm using the "Simple Error Handler VI" to check for errors.)
    I've also tried different options in the DSN configuration without any results.
    Attachments:
    TestProgram.vi ‏16 KB
    DSNconfig1.jpg ‏36 KB
    DSNconfig2.jpg ‏49 KB

    Also,
    I've duplicated the OPs example: a simple VI that opens and closes a connection. I can say this definately causes a memory leak.
    Watching the memory:
    10:17AM - 19308K
    10:19AM - 19432K
    10:22AM - 19764K
    10:58AM - 22124K
    Regards,
    Ken
    Attachments:
    OpenCloseConnection.vi ‏13 KB

  • Makequeues memory leak when using Lexmark Z53

    Behavior with printer switched off while connected to built-in USB port:
    Problem 1: makequeues has a memory leak, starting up with between 3 and 5 MB of RAM. This is done by connecting the printer when logged in and watching via Activity Monitor.
    Initially makequeues has sent 255 Mach messages. Every ~10.5 seconds, makequeues sends 59 more messages and gets 53 in reply. With each send/receive cycle, its RAM usage grows by 8 KB, a rate of 780 kiB/min.
    Problem 2: The process is started each time the same printer is reconnected.
    Symptoms: Disconnecting the printer doesn't let the process exit (any instance). If left alone, the memory usage cycle continues.
    The memory leak caught my attention after taking up over a half-gigabyte of RAM when I left the Mac running over night.
    Resolution:
    (1) Disconnect USB cable
    (2) Kill each instance of the process
    Results:
    (1) The process launches after reconnection of the printer with 996 KB of RAM, immediately having sent 60 Mach messages and received 56.
    (2) During this run time, the process may use less and less RAM, down to a minimum of 912.
    (3) After sending 64 more messages without replies, one every 4 seconds, the process exits after having sent a total of 120 messages.
    (4) This behavior (1 through 3) is the same for each process launched as a result of printer reconnection.
    This behavior isn't shown during Safe Mode boot - makequeues never starts up as a result of printer connection.
    PowerMac G4 QuickSilver 2001 733Mhz

    If this is meant to be a bug report, please file a bug report in the proper place. This is a user to user discussion forum.
    As to the source of running 'makequeues' (/System/Library/SystemConfiguration/PrinterNotifications.bundle/Contents/MacOS /makequeues), I would look at the Lexmark software. I currently have two Epson printers connected via USB with CUPS running. I see no process 'makequeues' appearing.
    Matt

Maybe you are looking for

  • Changing data types in database

    Hi, We are using Oracle 10g database. We changed the data type from DateTime to DateTimestamp. There are a whole bunch of joins defined in Discoverer's EUL. is there a work around this as all the reports written is not working because of this change?

  • Possible fix for Stubnotfound exception

    It seems like a lot of people are getting errors like "Unmarshalling exception", "Classnotfound....Stub", where the generated stubs are not being found by the registry, even though they're clearly there. I played around with this, and I thought I'd e

  • PCA report drill down

    Hi, When I drilldown PCA report S_ALR_87013343 to look up the original document, it takes me to PCA_FB03 transaction and gives an error "Enter Document Number". I imported all the reports and generated them again. Still the problem continues. What co

  • Canon printer problem after upgrade.

    Upgraded iMac to Yosemite 10.10.2.  Now my  Canon printer LPB6000-LPB6018 does not respond to print request.  Even tho the printer is fairly new, I have forgotten what the procedure was in setting it up with Maverick that came with the Mac.  Can it b

  • C++ builder 6 unresolved external error loading a dll

    Im using LabVIEW 6.1 and i'm trying to export a DLL that performs math routines (such as FFT and stuff..) to include it im my BC#B6 project. I chose the C Calling convention (because the Standard Calling Convention cannot be converted by the Coff2omf