Question

I've tried to search similiar question to this, but couldn't find. I don't know how i can stop my sound when button is released, and also, i don't know how to loop sound only one by one, when i hold button it plays again while previous loop is still playing, and the sound is becoming a loop from ∞ sounds.

Here's the code:

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Component;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;

public class test {

    String  b[]={"Q","W","E","R","T","Y","U","I","O","P","A","S","D","F","G","H","J","K","L","Z","X","C","V","B","N","M"};
    Action[] actions = new AbstractAction[26];

    public test() throws Exception {

        JFrame frame = new JFrame();

        JButton[] buttons = new JButton[26];

        for(int i = 0; i < buttons.length; i++) {
            buttons[i] = new JButton(b[i]);
            buttons[i].setSize(80, 80);
            buttons[i].addKeyListener(new KeyAdapter(){

                public void keyPressed(KeyEvent e){
                        System.out.println(e.getKeyChar());
                        playSound(new File("loopbase/loop1/"+e.getKeyChar()+".wav"));
                }

                public void keyReleased(KeyEvent e){

                }

            });
            frame.add(buttons[i]);
        }

        JPanel contentPane = (JPanel)frame.getContentPane();

        frame.setLayout(new GridLayout(3, 5, 5, 3));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                try {
                    new test();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

    }

    public void playSound(File soundName)
    {
      try 
      {
       AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundName.getAbsoluteFile( ));
       Clip clip = AudioSystem.getClip( );
       clip.open(audioInputStream);
       clip.start( );
      }
      catch(Exception ex)
      {
        System.out.println("Error with playing sound.");
        ex.printStackTrace( );
      }
    }

}

Anyone can help me with this issue?

Was it helpful?

Solution

I don't know how i can stop my sound when button is released?

You can stop the the clip by using DataLine#stop(). Just keep the reference of last played clip and call below line to stop it.

clip.stop();

Note: You can store it somewhere in static variable.


Sample code:

private static Clip clip;

...
public void keyReleased(KeyEvent e) {
    if (clip != null) {
        clip.stop();
    }
}
...

public void playSound(File soundName) {        
        ...
        clip = AudioSystem.getClip();            
        ...        
}

OTHER TIPS

When I hold the Button it plays again while previous loop is still playing.

This is because for every keyPress you are creating a new File object. That should be avoided.

To stop sound: I would add a boolean parameter to playsound method. And depending upon the parameter passed I would call clip.start() or clip.stop() (superclass DataLine has a stop method) . Call playsound(filename,false); in keyReleased.

public void playSound(File soundName , boolean start)
{

    try 
    {

        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundName.getAbsoluteFile( ));
        Clip clip = AudioSystem.getClip( );
        clip.open(audioInputStream);
        if(start == true)
        clip.start();
        else
        clip.stop();

    }
    catch(Exception ex)
    {

        System.out.println("Error with playing sound.");
        ex.printStackTrace( );

    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top