Erratic sound playback using Clip (javax.sound.samled)

Hi,
I have recently delved into writing an application with sound using Scala. Sound does play but seems rather unreliable across systems. For instance, only the long sounds are audible on my Ubuntu 9.04 system (OpenJDK 6b14-1.4.1-0ubuntu11). Interestingly on my windows PC running Vista Home with Sun JRE (build 6.1.0_15-b3) only the short sounds are audible and the longer sounds are cut off.
Before reporting bugs at OpenJDK and Sun respectively I would like to know if there is anything that I need to pay extra attention to. My programs "play" method is as follows:
Tuple2 sound = audioResources(name)
Clip clip = AudioSystem.getLine(sound.getInfo()).asInstanceOf[Clip]
AudioInputStream stream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(sound sound.getByteArray()))
clip.open(stream)
clip.start()Have adapted my code from Scala to Java somewhat. I am assuming that clip.start() works asynchronously. Hope can give me some pointers on how to get this to work correctly.
Best,
Dirk Louwers

Well, that's kind of a weird way of doing that... I would have done...
Clip c = AudioSystem.getClip();
AudioInputStream stream = AudioSystem.getAudioInputStream(new ByteArrayInputStream(sound sound.getByteArray()));
clip.open(stream);
clip.start();Anyway, clip.start() does work asyncronously, so you'll want to make sure your program isn't terminating before the clip has time to play.

Similar Messages

  • Beeper - loopable sound using Clip.

    // <applet code='Beeper' width='300' height='300'></applet>
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.border.*;
    import java.text.DecimalFormat;
    import javax.sound.sampled.*;
    import java.io.ByteArrayInputStream;
    /** Beeper presents a small, loopable tone that can be heard
    by clicking on the Code Key.  It uses a Clip to loop the sound,
    as well as for access to the Clip's gain control.
    @author Andrew Thompson
    @version 2009-12-19
    @license LGPL */
    public class Beeper extends JApplet {
    public void init() {
      getContentPane().add(new BeeperPanel());
      validate();
    public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
       public void run() {
        JFrame f = new JFrame("Beeper");
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        BeeperPanel BeeperPanel = new BeeperPanel();
        f.setContentPane(BeeperPanel);
        f.pack();
        f.setMinimumSize( new Dimension(300,300) );
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    /** The main UI of Beeper. */
    class BeeperPanel extends JPanel {
    JComboBox sampleRate;
    JSlider framesPerWavelength;
    JLabel frequency;
    JCheckBox harmonic;
    Clip clip;
    DecimalFormat decimalFormat = new DecimalFormat("###00.00");
    BeeperPanel() {
      super(new BorderLayout());
      JPanel options = new JPanel();
      BoxLayout bl = new BoxLayout(options,BoxLayout.Y_AXIS);
      options.setLayout(bl);
      Integer[] rates = {
       new Integer(8000),
       new Integer(11025),
       new Integer(16000),
       new Integer(22050)
      sampleRate = new JComboBox(rates);
      sampleRate.setToolTipText("Samples per second");
      sampleRate.setSelectedIndex(1);
      JPanel pSampleRate = new JPanel(new BorderLayout());
      pSampleRate.setBorder(new TitledBorder("Sample Rate"));
      pSampleRate.add( sampleRate );
      sampleRate.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent ae) {
        setUpSound();
      options.add( pSampleRate );
      framesPerWavelength = new JSlider(JSlider.HORIZONTAL,10,200,25);
      framesPerWavelength.setPaintTicks(true);
      framesPerWavelength.setMajorTickSpacing(10);
      framesPerWavelength.setMinorTickSpacing(5);
      framesPerWavelength.setToolTipText("Frames per Wavelength");
      framesPerWavelength.addChangeListener( new ChangeListener(){
       public void stateChanged(ChangeEvent ce) {
        setUpSound();
      JPanel pFPW = new JPanel( new BorderLayout() );
      pFPW.setBorder(new TitledBorder("Frames per Wavelength"));
      pFPW.add( framesPerWavelength );
      options.add( pFPW );
      JPanel bottomOption = new JPanel( new BorderLayout(4,4) );
      harmonic = new JCheckBox("Add Harmonic", false);
      harmonic.setToolTipText(
       "Add harmonic to second channel, one octave up");
      harmonic.addActionListener( new ActionListener(){
       public void actionPerformed(ActionEvent ae) {
        setUpSound();
      bottomOption.add( harmonic, BorderLayout.WEST );
      frequency = new JLabel();
      bottomOption.add( frequency, BorderLayout.CENTER );
      options.add(bottomOption);
      add( options, BorderLayout.NORTH );
      JPanel play = new JPanel(new BorderLayout(3,3));
      play.setBorder( new EmptyBorder(4,4,4,4) );
      JButton bPlay  = new JButton("Code Key");
      bPlay.setToolTipText("Click to make tone!");
      Dimension preferredSize = bPlay.getPreferredSize();
      bPlay.setPreferredSize( new Dimension(
       (int)preferredSize.getWidth(),
       (int)preferredSize.getHeight()*3) );
      // TODO comment out to try KeyListener!
      bPlay.setFocusable(false);
      bPlay.addMouseListener( new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent me) {
         loopSound(true);
        @Override
        public void mouseReleased(MouseEvent me) {
         loopSound(false);
      play.add( bPlay );
      try {
       clip = AudioSystem.getClip();
       final FloatControl control = (FloatControl)
        clip.getControl( FloatControl.Type.MASTER_GAIN );
       final JSlider volume = new JSlider(
        JSlider.VERTICAL,
        (int)control.getMinimum(),
        (int)control.getMaximum(),
        (int)control.getValue()
       volume.setToolTipText("Volume of beep");
       volume.addChangeListener( new ChangeListener(){
        public void stateChanged(ChangeEvent ce) {
         control.setValue( volume.getValue() );
       play.add( volume, BorderLayout.EAST );
      } catch(Exception e) {
       e.printStackTrace();
      add(play, BorderLayout.CENTER);
      setUpSound();
    /** Sets label to current frequency settings. */
    public void setFrequencyLabel() {
      float freq = getFrequency();
      if (harmonic.isSelected()) {
       frequency.setText(
        decimalFormat.format(freq) +
        "(/" +
        decimalFormat.format(freq*2f) +
        ") Hz" );
      } else {
       frequency.setText( decimalFormat.format(freq) + " Hz" );
    /** Generate the tone and inform the user of settings. */
    public void setUpSound() {
      try {
       generateTone();
       setFrequencyLabel();
      } catch(Exception e) {
       e.printStackTrace();
    /** Provides the frequency at current settings for
    sample rate & frames per wavelength. */
    public float getFrequency() {
      Integer sR = (Integer)sampleRate.getSelectedItem();
      int intST = sR.intValue();
      int intFPW = framesPerWavelength.getValue();
      return (float)intST/(float)intFPW;
    /** Loops the current Clip until a commence false is passed. */
    public void loopSound(boolean commence) {
      if ( commence ) {
       clip.setFramePosition(0);
       clip.loop( Clip.LOOP_CONTINUOUSLY );
      } else {
       clip.stop();
    /** Generates a tone, and assigns it to the Clip. */
    public void generateTone()
      throws LineUnavailableException {
      if ( clip!=null ) {
       clip.stop();
       clip.close();
      } else {
       clip = AudioSystem.getClip();
      boolean addHarmonic = harmonic.isSelected();
      int intSR = ((Integer)sampleRate.getSelectedItem()).intValue();
      int intFPW = framesPerWavelength.getValue();
      float sampleRate = (float)intSR;
      // oddly, the sound does not loop well for less than
      // around 5 or so, wavelengths
      int wavelengths = 20;
      byte[] buf = new byte[2*intFPW*wavelengths];
      AudioFormat af = new AudioFormat(
       sampleRate,
       8,  // sample size in bits
       2,  // channels
       true,  // signed
       false  // bigendian
      int maxVol = 127;
      for(int i=0; i<intFPW*wavelengths; i++){
       double angle = ((float)(i*2)/((float)intFPW))*(Math.PI);
       buf[i*2]=getByteValue(angle);
       if(addHarmonic) {
        buf[(i*2)+1]=getByteValue(2*angle);
       } else {
        buf[(i*2)+1] = buf[i*2];
      try {
       byte[] b = buf;
       AudioInputStream ais = new AudioInputStream(
        new ByteArrayInputStream(b),
        af,
        buf.length/2 );
       clip.open( ais );
      } catch(Exception e) {
       e.printStackTrace();
    /** Provides the byte value for this point in the sinusoidal wave. */
    private static byte getByteValue(double angle) {
      int maxVol = 127;
      return (new Integer(
       (int)Math.round(
       Math.sin(angle)*maxVol))).
       byteValue();
    }

    This code was written (rather belatedly) in response to a question in [Example: Code to generate audio tone|http://forums.sun.com/thread.jspa?threadID=5243872]. Due to it's age, it has been locked.
    The replier wanted to know how to use JavaSound for a Morse code key. Actually now I think about it, the sound loops nicely, but it still demonstrates a slight click at start and stop. I tried using Clip.loop(0) to stop the sound, but that did not avoid the 'click'! I suppose you would need to do as the person was musing, and adjust the GAIN of the Clip up and down.
    In any case - questions.
    - Can anyone make this work for key presses? The first thing you'd need to do is a find on "TODO" and comment out the line that ensures the Code Key is not focusable (and then add a KeyListener(1)). The problem I encountered was that the KeyEvents were getting fired continuously, which caused the sound to 'stutter'. A Timer to ignore quickly repeated keys might work (though I could not make it work for me), but then that would introduce a lag between when whe key was released, and when the sound stopped. It would need to be a very short delay, to use it much in the way the mouse click currently works.
    - Any ideas on improvements to the basic code? (1) (I will be adding the ability to configure the parameters of the applet - more code lines. Possibly also converting the GAIN control from the mostly useless logarithmic ..whatever scale it uses, to linear.)
    1) Note that I had to use single spaces to indent - everything else blew the posting limit(2).
    2) Hence also, questions on 2nd post. ;)
    To compile and run as an applet/application (in a recent SDK).
    javac Beeper.java
    appletviewer Beeper.java
    java BeeperEdit 1:
    Latest source can be found at [http://pscode.org/test/eg/Beeper.java]. See also the [formatted version|http://pscode.org/fmt/sbx.html?url=%2Ftest%2Feg%2FBeeper.java&col=2&fnt=2&tab=2&ln=0].
    Edited by: AndrewThompson64 on Dec 19, 2009 1:50 PM

  • Audio playback is clipped and has low volume

    Hi, I'm hoping that someone can help me debug my audio problems.
    The problem is that audio playback is clipped and has low volume.
    The details of my setup are as follows:
    - An onboard soundcard (ASUS M4A78LT-M-LE motherboard), identified as Intel HDA in dmesg:
    description: Audio device
    product: SBx00 Azalia (Intel HDA)
    vendor: ATI Technologies Inc
    physical id: 14.2
    bus info: pci@0000:00:14.2
    version: 00
    width: 64 bits
    clock: 33MHz
    capabilities: pm bus_master cap_list
    configuration: driver=snd_hda_intel latency=64
    resources: irq:16 memory:f9ff4000-f9ff7fff
    - ALSA (snd_hda_intel driver) and Pulseaudio
    My ALSA mixer settings (which were used in the recording shown in this post) are at pastebin.
    The mixer settings were chosen so that all "dB gain" is 0.00 for all columns in alsamixer.
    Recording an MP3 (played at full volume) from the Stereo Mixer source in audacity I gives output which looks clipped and has low volume (link).
    This occurs with any MP3 and any other sound source (Youtube in Chromium, etc.)
    The problem does not occur when I boot into Windows XP, so it doesn't seem to be a hardware problem.
    I'm also attaching a screenshot of my alsamixer playback screen for the soundcard (link)
    Thanks for any assistance!

    Hi,
    I have the same problem since December 2011 with a similar Mainboard (Asus M4A78T-E).
    Did you resolve your problem?
    Thanks

  • Disrupted Playback using AirTunes/Airport Express

    I've been having intermittent trouble with playback using Airtunes. Songs will play, then cut out... the song is still progressing in iTunes, but with no sound. Sometimes it will flicker in and out. Sometimes it won't. Sometimes quitting and relaunching solves it. Sometimes it doesn't. Sometimes it coincides with when my Time Capsule is backing up. Sometimes not. It's infuriating to try to problem solve it because it's so sporadic.
    Tonight I can only get about 6 seconds of playback each time I double click on a song.
    Is anyone else having these difficulties besides me and my Mom (who doesn't live here and has her own setup that's not working?)

    This has been on ongoing problem.... I was hoping that iTunes 10 would have found a way to resolve this... But alas this is not the case as it is the very problem that brought me to the discussion boards today. It is infuriating as AirTunes is my only music resource at home. I have been using it for the past five years and the problem of the sound cutting out and/or sputtering is no better now than it was back in 2005 when I first started using it.
    It is downright embarrassing when I have guests over and the music constantly cuts out... Makes convincing my PC fan friends why they should switch to Apple a bit more challenging.
    You would think that with all the resources Apple has at their beck and call, they could make AirTunes actually function as described... But clearly this is not a priority. Sad really...
    Message was edited by: 24gotham

  • Change volume and Balance of speaker using Clip interface

    Hello,
    I am playing more than one Clip simulteniously. I want to change the volume and balance of individual Clip so that they have individual effect on speaker. I mean, if there are two clip then one should have high sound and other have low like that.
    Any help would be appreciated.
    Thanks in Advance.

    Hello,
    I play a sound using Clip interface in Java Sound. i am able to get FloatControl.Type.MASTER_GAIN) control but not FloatControl.Type.PAN)
    I have written a code like this,
    FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.PAN);
    Any help would be appreciated.
    * Thanks In advance*

  • HOW TO USE CLIPS FROM A DVD???

    HOW TO USE CLIPS FROM A DVD???
    i know this may be a stupid and obvious question but i can't seem to figure it out.
    these are not copyrited dvds... mostly home movies and old home movies put onto dvd.
    thank you... much appreciated.

    Studio X has given one suggestion.
    MPEG Streamclip is another:-
    http://www.squared5.com/
    It is free but your computer may not have the QT MPEG 2 Playback Component which costs $20 from Apple as a download.
    If you have access to an Analogue-DV converter you can use that. Also a DV camcorder which has Analogue IN.
    If you have Final Cut Pro installed, you will have the QT component.
    Message was edited by: Ian R. Brown

  • I'm seeing a strobing effect during playback of clips and timeline in FCP7. How do I fix?

    I'm seeing a strobing effect during playback of clips and the timeline in FCP7. Footage isn't corrupt. Apple techs said its not hardware after their tests at the Apple store. I did a full reinstall of FCS. There's 4GB of RAM free at all times during playback. The problem is still there... How do I fix this?
    Strobing:
    By strobing, I mean there's only about 1 ever 10 frames playing back for me. Everything is rendered and the comp settings match the clip settings. It's not constant though, but the strobing is triggered at certain points on the timeline and effect a few clips after that (10 seconds or so at a time), and then when the next clip is displayed on the timeline the strobbing stopps and is reset back to normal playback... until another random clip is encountered by the playback head to which then the process repeats. Also, when strobbing is happening and I move the playhead back a few seconds, or pause & play, or even forward a little on the same strobbing clip (basically when i inturrupt the playback process) the strobbing STOPS! I can watch the same footage that was strobing without it strobing any longer until I move back the playhead far enough and try again, then the strobing is triggered again. I hope this all makes sense, it's very picular and I've seen or heard of nothing like it in my 4 years of editing in FCP7.

    SStrange my enough the problem started occurring a few hours into the project. The only thing I can think of is that I shot with all Canon 5D mark iii footage when I usually shot with a mark ii. My workflow hasn't changed and I have never had this problem. I've also used other mark iii footage in the past without a problem but I don think I've edited entirely with mark iii footage

  • Has fix been found to playback of clip audio in the ingest window??

    Has a fix been introduced in Prelude that allows playback of clip audio from the ingest window?  I read the discussion thread and  it left off with the comment that Adobe is aware of isse and working on fix.  I am using CC 2014 and the issue still exists.Hearing clip audio in the ingest window...has a fix been found???

    Strangely enough the pref file did not show up in the Preferences folder.  I don't know what this means but it could be signifigant.

  • How do I use clipping mask to cover unwanted background?

    I'm practicing illustrator myself. I have a book for illustrator hoping it would show me step by step on how to use the masks to take away any unwanted background in a photo but it didn't do that. Can anyone teach me how or show me where to look for the information on how to use the clipping masks or other type of masks? I went to the adobe workshop video to look for the answer but it didn't show exactly as what i want to know. The image i'm practicing on is a family photo and i want to isolate everything to just one person in the photo so how can I do that using clipping mask? Thanks!!

    oh~~~ so i still need to use pen tool to draw the shape out. I thought there's something i could use to make the shape easily. Stupid me XD
    I was wondering if you could help me more...can you give me a rule of thumb like when is best to use illustrator to edit image or photoshop?
    Thanks for your tip! I really appreciate it!!
    =D
    Sometimes the only way to stay sane is to go a little crazy. -
    "Girl, Interrupted"
    It is the journey itself which makes up your life. -
    Tiresias, the blind prophet, "The Odyssey"
    Date: Thu, 18 Feb 2010 02:00:41 -0700
    From: [email protected]
    To: [email protected]
    Subject: How do I use clipping mask to cover unwanted background?
    Draw the mask using the pen tool over the image. Select both the drawn mask AND image and choose Object > Clipping Mask > Make
    >

  • Is there a way to automatically hide used clips??

    is there a way to hide the used clips??
    iMovie 10.0.4

    You can capture the complete clip and then apply Mark > DV Start/Stop Detect over the captured clip. You could get the best of two worlds so: smooth capture and clips creation.

  • What is the benefit of using clipping paths for a knock out?

    I found a posting saying they need someone to knock out the background of a lot of images using clipping paths. My question is, WHY use a clipping path? I know the rule of not using a selection tool such as the Magic Wand and then turning it into a clipping path and I know why that is. But if all is needed is for the background to be knocked out, why can't we just use the selection tool in the first place and just knock out the background from there? What is the benefit of that clipping mask?

    Usually the term Clipping Path refers to turning a path into a clipping path (in the paths panel) for use in older programs such as PageMaker that don't support transparency.
    For example if one wanted to import a file into PageMaker and only have a certain part of the document visible, one would make a path (or selection) around the object
    and turn the path (or selection) into a clipping path. Sorta the same results you see in photoshop using a layer mask or vector mask.
    Also clipping paths are used in certain printing workflows.
    Without seeing the posting it's hard to say what they meant and in photoshop 6 vector masks were labeled as Layer Clipping Paths not to be confused with real clipping paths.
    Old versions of photoshop also used the term Group With Previous to denote Create Clipping Mask.
    photoshop 6:
    Photoshop cs6:
    Anyway clipping masks and clipping paths are two different things in photoshop.
    layer masks, vector masks and clipping masks:
    http://helpx.adobe.com/content/help/en/photoshop/using/masking-layers.html
    an example of creating a clipping path:
    http://www.clippingpathspecialist.com/tutorials.html

  • AI CS6 vectors turn into embedded image when using clipping mask

    AI CS6 vectors turn into embedded image when using clipping mask, how to solve it?

    With the Clipping Mask selected go here

  • Where has "Duplicate Project + Used Clips" gone in 10.2 ?

    I want to backup my project and all the media it uses to an external hard drive.
    In 10.1 I could use, Duplicate Project + Used Clips , but where is that in 10.2?

    I'm assuming you mean 10.1.2, not 10.0.2. For the recent version, connect the external drive. Make a new library on it and set the library properties to be managed media, so the media in inside the library. Drag the project from the existing event on your drive to the event on the external drive, that will copy the project and the used media to that event. You'll also have the option to copy render and optimized media. I'd forget about that. Mail the drive and your colleague should be good to go.

  • Media Foundation:Playback using Raw Data Bytes Frame by Frame

    I have a stream of bytes encoded by H264.Now
    I want to playback using Media Foundation I have the frames as raw data without container and I receive it frame by frame.does any
    one have any idea how can I do that?

    You should be able to decode it with the MF H264 decoder, but you should get the codec private data from the encoder in order to configure the decoder (MF_MT_USER_DATA). Anyway, more info on this would probably help other people in providing useful answers.
    Once you have decoded frames you could render them with the EVR or DXVA.

  • Duplicate Project + Used Clips Only not working as expected.

    I am revisiting this once again and have had some good information on the matter, but I am not getting the results I think I should.
    Here's a link of instructions I followed and addresses my exact concern:  http://www.premiumbeat.com/blog/how-to-archive-projects-in-final-cut-pro-x/
    I want to archive ONLY the project and clips used for a project. 
    If I export my project using the current settings (ProRes) then shouldn't the Duplicate Project and Used Clips only feature give me a a backup that is roughly the same size as my exported Quicktime?
    Currewntly when I use any of the Duplicate operations other than the 1st, all media is duplicated, not just what is needed.
    Has anyone had success with just getting what you need for the project?
    The reason why I don't want to archive all of the media outside the project is due to hard drive space.  I have the camera raws backed up already.  I just want to be able to open the project again if needed and only the project with necessary media.
    Thanks.

    When you say " I also changed the default start to 7:30 and end 4:30", are you talking about the
    project information in the project tab? You're supposed to be able to specify only one of the parameters (start date or finish date) depending if you're back-planning or not.
    Check if the option "ignore resource calendar" on the task if checked.
    Also try to press F9.
    Are the task manually scheduled? Do you have constraints on the tasks?
    Maybe share a screenshot so it'll be easier to help you.
    Hope this helps,
    Guillaume Rouyre, MBA, MCP, MCTS |

Maybe you are looking for

  • Sun Directory Editor - errors on edit form

    I've installed directory editor, which seems to run fine except for the edit form. I've got the following errors in the server.log (running Sun Java System Application Server Platform Edition 8.2) and can't find any doc on how to solve this. [#|2009-

  • BPM 7.2 : Route the task to a person holding a position in the Org Unit

    Hi, Consider the below HR scenario: I have a leave application which goes from an employee to Manager for approval. I have this currently designed based on workflows (using Org Structure positions in my ECC HR System). Nowhere I have hard coded the u

  • Is it possible to blur faces in Pro X?

    I just purchased the program and can't figure out how to blur faces. Is this possible?

  • Aperture 3.3 Bug: Syncing Stacks Syncs All Versions, Not Just Pick

    Aperture 3.3 has a pretty significant bug.  Syncing to iOS devices results in all versions in a Stack to be synced to the device, not just the Picks.  This is a HUGE problem as two things happen: 1) The amount of space consumed by the versions can be

  • Execute stored procedure as sysadmin

    Hi, I am running powershell script to execute stored procedure on SQL server. Powershell script is run with low privilege user account on SQL server, but SP is restoring databases and requires sysadmin permissions. How can I execute SP with sysadmin