Page 1 of 2 12 LastLast
Results 1 to 20 of 25
  1. #1
    robs is offline Member
    Join Date
    Feb 2011
    Posts
    58
    Rep Power
    0

    Default Playing audio clips

    I have a game which implements Swing. The game has several .wav files which it loads and runs as audioclips. The audioclips are always run on a new thread. My problem is that the sound does not always play. For example, I have three radio buttons which make a noise every time the mouse enters. If I move the mouse up and down over the three buttons, sometimes the noise plays twice and sometimes three times. I'm not moving the mouse particularly quickly (slowly enough to give each noise time to play) and even when I move it more quickly, the noise will sometimes play three times. This is the code for playing the audioclip, I have used a SwingWorker as playSound() is run on the EDT:

    Java Code:
    private AudioClip toPlay;
    protected void playSound(AudioClip[] a) {
        if(volume != 0) { 
            toPlay = a[volume];
            new SwingWorker<Void, Void>() {
                    @Override
                protected Void doInBackground() {
                    System.out.println(toPlay);
                    toPlay.play();
                    System.out.println("play sound done");
                    return null;
                }
            }.execute();
        }
    }
    I wonder if the problem has something to do with me assigning the AudioClip outside of the SwingWorker. The print lines show that the toPlay is not null and that even when the sound doesn't play, doInBackground is running. Is this the correct way to use sounds? Do I need to use a SwingWorker? I have seen that if you use Clip, a Thread is automatically created, does the same apply for audioclip? Is it better to use Clip?

    Thanks in advance,

    Rob

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Playing audio clips

    Are you using mouse listeners to start the sound? How many times do you add a listener to a component? Could a listener be added more than once?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    robs is offline Member
    Join Date
    Feb 2011
    Posts
    58
    Rep Power
    0

    Default Re: Playing audio clips

    Hi,

    Thanks for your reply. The mouselistener is only added once, when the panels are all loaded:

    radioButton = new MyRadioButton[3];
    radioButton[0] = new MyRadioButton(this, 0);
    radioButton[1] = new MyRadioButton(this, 1);
    radioButton[2] = new MyRadioButton(this, 2);
    for(MyRadioButton rad : radioButton) {
    rad.unavailable();
    rad.setOpaque(false);
    rad.addMouseListener(this);
    }

    This is the listener code:

    Java Code:
    public void mouseEntered(MouseEvent e) {
        if(e.getComponent() instanceof MyButton) {
            for(int i = 0 ; i < button.length ; i++) {
                if(e.getComponent() == button[i] && button[i].available) {
                    button[i].entered();
                }
            }
        }
        if(e.getComponent() instanceof MyRadioButton) {
            for(int i = 0 ; i < radioButton.length ; i++) {
                if(e.getComponent() == radioButton[i] &&
                              radioButton[i].available) {
                    if(!radioButton[i].selected) {
                        radioButton[i].entered();
                        playSound(radioB);
                    }
                }
            }
        }
    }

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Playing audio clips

    When do you expect playSound() to be called when you have the mouse moving over all the radio buttons?
    Have you tried seeing when it is called by adding a println()s in the mouse listener to print messages on the different states of the variables used to control when playSound() is called?
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    robs is offline Member
    Join Date
    Feb 2011
    Posts
    58
    Rep Power
    0

    Default Re: Playing audio clips

    I'm not sure if I completely understand your question, so excuse me if this answer is irrelevant. The println()s in playSound() show that play sound is running every time the mouse enters a radio button, which is what should happen. The problem is that it somtimes doesn't play the sound. Looking at it now, I'm wondering if redefining toPlay each time could affect it.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Playing audio clips

    somtimes doesn't play the sound.
    Are you saying that some calls to the play() method do not play the sound?

    Try moving the toPlay variable inside of the SwingWorker class definition so it wouldn't be changed.
    Last edited by Norm; 06-13-2012 at 03:30 PM.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    robs is offline Member
    Join Date
    Feb 2011
    Posts
    58
    Rep Power
    0

    Default Re: Playing audio clips

    Yes, sorry, I should have made that clearer. I am now wondering if it could be because my EDT is doing some things it shouldn't be doing (specifically sending and receiving data). I know that that can cause strange problems. Perhaps I should sort the EDT out and come back to this if the problem persists?

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Playing audio clips

    Yes, you should keep the use of the EDT clean.

    Try moving the toPlay variable inside of the SwingWorker class definition so it wouldn't be changed.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    robs is offline Member
    Join Date
    Feb 2011
    Posts
    58
    Rep Power
    0

    Default Re: Playing audio clips

    The reason toPlay is outside the SwingWorker is because the method is used for other AudioClips too. The argument for the method is the AudioClip, toPlay is assigned that AudioClip so it has to be outside the SwingWorker because the SwingWorker cannot see the argument.

    I'll clean up the EDT as soon as I can and then return to this, otherwise I might be wasting your time.

    Thanks again,

    Rob

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Playing audio clips

    If each instance of a new SwingWorker had its own copy of toPlay then there would be no conflicts between multiple instances of SwingWorker objects. Now it is possible for the value of toPlay to be changed before the play() method is called.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    robs is offline Member
    Join Date
    Feb 2011
    Posts
    58
    Rep Power
    0

    Default Re: Playing audio clips

    I tried this, but the result was the same:

    Java Code:
    private AudioClip clip;
    protected void playSound(AudioClip[] a) {
        if(volume != 0) { 
            clip = a[volume];
            new SwingWorker<Void, Void>() {
                    @Override
                protected Void doInBackground() {
                    AudioClip toPlay = clip;
                    toPlay.play();
                    return null;
                }
            }.execute();
        }
    }
    I'll clean up the EDT and come back to this.

  12. #12
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Playing audio clips

    Can you make a small program that compiles, executes and shows the problem?
    If you don't understand my response, don't ignore it, ask a question.

  13. #13
    robs is offline Member
    Join Date
    Feb 2011
    Posts
    58
    Rep Power
    0

    Default Re: Playing audio clips

    This demonstrates the problem. If I run the mouse slowly (about 1 sec per button) over the three buttons, all the sounds play but when I do it a little faster (about 1 sec for all buttons), sometimes (probably about 1 in 4 times) one of the sounds does not play. It will be interesting to see if you have the same problem, perhaps it's something to do with my computer! The sound itself is less than a tenth of a second long, let me know if it's any help if I send you it. Thank you.

    Java Code:
    package testsound;
    
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.FontRenderContext;
    import java.awt.font.LineBreakMeasurer;
    import java.awt.font.TextLayout;
    import javax.swing.*;
    import java.net.URL;
    import java.text.AttributedCharacterIterator;
    import java.text.AttributedString;
    
    
    public class Test_Sound extends JApplet implements MouseListener{
    
        @Override
    public void init() {
       try {
           javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
               public void run() {
                   createGUI();
               }
           });
       } catch (Exception e) {
           System.err.println("createGUI unsuccessful");
       }
       audioWorker.execute();
    }
    
    private void createGUI() {
        System.out.println("Progress bar here in full program");
    }
    
    private String audioNames[] = {
        "radio"  
    };
    AudioClip wavs[];
    AudioClip radioB[];
    private final int VOLUME = 1;
    SwingWorker audioWorker = new SwingWorker<AudioClip[], Void>() {
        @Override
        public AudioClip[] doInBackground() {
            final AudioClip[] innerClips = new AudioClip[audioNames.length*VOLUME];
            for (int i = 0; i < audioNames.length; i++) {
                for (int j = 0 ; j < VOLUME ; j++) {
                    innerClips[(i*VOLUME)+j] = myGetAudioClip(audioNames[i] + ".wav");
                }
            }
            return innerClips;
        }
    
            @Override
        public void done() {
            try {
                wavs = get();
            } catch (InterruptedException ignore) {}
            catch (java.util.concurrent.ExecutionException e) {
                String why = null;
                Throwable cause = e.getCause();
                if (cause != null) {
                    why = cause.getMessage();
                } else {
                    why = e.getMessage();
                }
                System.err.println("Error retrieving file: " + why);
            }
    
            radioB = new AudioClip[VOLUME];
            radioB[0] = wavs[0];
            loadPanels();
        }
    };
    
    private AudioClip myGetAudioClip(String s) {
    //System.out.println(s);
        AudioClip clp;
        URL url  = getClass().getResource("audio/" + s);
    //System.out.println("get " + url);
        clp = getAudioClip(url);
        return clp;
    }
    
    MyRadioButton radioButton[];
    private void loadPanels() {    
        radioButton = new MyRadioButton[3];
        radioButton[0] = new MyRadioButton(0, 30, "RADIO 1");
        radioButton[1] = new MyRadioButton(1, 30, "RADIO 2");
        radioButton[2] = new MyRadioButton(2, 30, "RADIO 3");
        for(MyRadioButton rad : radioButton) {
            rad.available();
            rad.setOpaque(false);
            rad.addMouseListener(this);
        }
    
        JPanel panel = new JPanel();
        panel.setSize(new Dimension(150, 150));
        panel.setSize(new Dimension(150, 150));
        panel.setSize(new Dimension(150, 150));
        panel.setSize(new Dimension(150, 150));
        
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.add(Box.createRigidArea(new Dimension(0, 40)));
        panel.add(radioButton[0]);
        panel.add(radioButton[1]);
        panel.add(radioButton[2]);
        
        add(panel);
        
        validate();
    }
    
    
    /**********************MOUSELISTENER*******************/
    
    public void mousePressed(MouseEvent e) {}
    
    public void mouseReleased(MouseEvent e) {}
    
    public void mouseEntered(MouseEvent e) {
        if(e.getComponent() instanceof MyRadioButton) {
            for(int i = 0 ; i < radioButton.length ; i++) {
                if(e.getComponent() == radioButton[i] &&
                              radioButton[i].available) {
                    if(!radioButton[i].selected) {
                        radioButton[i].entered();
                        playSound(radioB);
                    }
                }
            }
        }
    }
    
    public void mouseExited(MouseEvent e) {    if(e.getComponent() instanceof MyRadioButton) {
            for(int i = 0 ; i < radioButton.length ; i++) {
                if(e.getComponent() == radioButton[i] &&
                              radioButton[i].available) {
                    if(!radioButton[i].selected) {
                        radioButton[i].exited();
                    }
                }
            }
        }
    }
    
    public void mouseClicked(MouseEvent e) {}
    
    private AudioClip clip;
    protected void playSound(AudioClip[] a) {
            clip = a[0];
            new SwingWorker<Void, Void>() {
                    @Override
                protected Void doInBackground() {
                    AudioClip toPlay = clip;
                    toPlay.play();
                    return null;
                }
            }.execute();
    }
    }
    
    class MyRadioButton extends JPanel {
    int width, height;
    public int number;
    String name;
    public boolean available, grey, entered, selected;
    
    public MyRadioButton(int num, int h, String s) {
        height = h;
        width = 80;
        number = num;
        name = s;
    
        fixSize();
    }
    
    private void fixSize() {
      setSize(new Dimension(width, height));
      setMaximumSize(new Dimension(width, height));
      setMinimumSize(new Dimension(width, height));
      setPreferredSize(new Dimension(width, height));
      repaint();
    }
    
    protected void select() {
        selected = true;
        repaint();
    }
    
    protected void deselect() {
        selected = false;
        repaint();
    }
    
    protected void unavailable() {
        available = false;
        grey = true;
        entered = false;
        repaint();
    }
    
    protected void available() {
        available = true;
        grey = false;
        repaint();
    }
    
    protected void entered() {
        entered = true;
        repaint();
    }
    
    protected void exited() {
        entered = false;
        repaint();
    }
    
        @Override
    protected void paintComponent( Graphics g ) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
    
        Color buttonBorderColor1 = new Color(0, 122, 244);
        Color buttonBorderColor2 = new Color(0, 0, 180);
    
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                       RenderingHints.VALUE_ANTIALIAS_ON);
    
        if(selected)
            g2d.setColor(new Color(84, 210, 67));
        else if(entered)
            g2d.setColor(new Color(84, 160, 67));
        else 
            g2d.setColor(Color.BLACK);
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                           RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        int x = 0/*(width - 25 - textWidth) / 2*/;
        int y = 19;
        AttributedString as = new AttributedString(name);
        AttributedCharacterIterator aci = as.getIterator();
        FontRenderContext frc = g2d.getFontRenderContext();
        LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
        TextLayout textLayout = lbm.nextLayout(this.getWidth());
        textLayout.draw(g2d, x, y);
    
        if(!entered)
            g2d.setColor(buttonBorderColor1);
        else 
            g2d.setColor(buttonBorderColor2);
        g2d.fillOval( width - 23, 8, 14, 14 );
        g2d.fillOval(width - 22 , 9 , 12, 12);
        g2d.setColor(Color.BLACK);
        g2d.drawOval(width - 21 , 11 , 8, 8);
        g2d.setColor(Color.WHITE);
        g2d.fillOval(width - 19 , 12 , 6, 6);
        if(selected) {
            g2d.setColor(Color.BLACK);
            g2d.fillOval(width - 18, 13, 4, 4);
        }
    }
    }

  14. #14
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Playing audio clips

    Have you tried printing out the time when play() is called for each clip? Are you expecting them to play serially or what happens if the calls come at the same time ie while one is already playing?

    I have no .wav files for testing.
    If you don't understand my response, don't ignore it, ask a question.

  15. #15
    robs is offline Member
    Join Date
    Feb 2011
    Posts
    58
    Rep Power
    0

    Default Re: Playing audio clips

    I haven't tried printing the time, how would that help? I was hoping that they would play simultaneously or, if not, that a new instance would interrupt any which is currently playing.

    What is the best way to send you the wav? I can't get the attachment function to work at the moment.

  16. #16
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Playing audio clips

    how would that help
    It would help you understand what the code is doing.
    How many different AudocClip objects are there? What happens if the play() method is called while it is still playing?
    Do you want the sounds to be blended/mixed so they all play at the same time? Or do you want each sound to play separately, one at a time? I don't know what the hardware does or what the software does when the program tries to play overlapping sounds.
    If you don't understand my response, don't ignore it, ask a question.

  17. #17
    robs is offline Member
    Join Date
    Feb 2011
    Posts
    58
    Rep Power
    0

    Default Re: Playing audio clips

    I will try printing out the time as soon as I can. Sorry to reply so sporadically, I just haven't had much time to look at it recently. Ideally I would like the sounds to be mixed, yes. I don't want one to wait for the previous one to finish. I would have thought overlapping sounds is doable. It would just be like having 2 media players open at the same time playing the same file wouldn't it?

    When you say AudioClip objects, what are you referring to? Do you mean how many AudioClips do I have in the whole program? There are 9 at the moment, but this is the only instance where two will be played at the same time.

    Thanks again for your time.

  18. #18
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Playing audio clips

    I can make the sounds play one at a time but i have no idea how to mix them.
    If you don't understand my response, don't ignore it, ask a question.

  19. #19
    robs is offline Member
    Join Date
    Feb 2011
    Posts
    58
    Rep Power
    0

    Default Re: Playing audio clips

    Do the sounds interrupt previous ones or wait for them to finish, if it's the former that's fine for me. Do they ever just not play? If not perhaps my problem is to do with my computer.

  20. #20
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,578
    Rep Power
    25

    Default Re: Playing audio clips

    I have no ideas on those questions. Write some test code and see what happens.
    If you don't understand my response, don't ignore it, ask a question.

Page 1 of 2 12 LastLast

Similar Threads

  1. playing wav files
    By treeface99 in forum New To Java
    Replies: 12
    Last Post: 02-07-2012, 12:12 PM
  2. Playing a WAV or MP3
    By meesterpickles in forum New To Java
    Replies: 7
    Last Post: 12-19-2011, 02:59 AM
  3. Video clips in side bar start playing automagically.
    By JosAH in forum Suggestions & Feedback
    Replies: 10
    Last Post: 05-26-2011, 09:01 AM
  4. Highlight text on playing audio
    By archanaanbu in forum Java Applets
    Replies: 1
    Last Post: 02-22-2011, 01:34 PM
  5. playing audio in J-App??
    By ashton in forum New To Java
    Replies: 3
    Last Post: 01-30-2009, 08:50 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •