EiKei EiKei - 1 year ago 96
Java Question

How to loop a sound while button is pressed and stop when released?

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){
playSound(new File("loopbase/loop1/"+e.getKeyChar()+".wav"));

public void keyReleased(KeyEvent e){



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

frame.setLayout(new GridLayout(3, 5, 5, 3));

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


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


Anyone can help me with this issue?

Answer Source

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.


Note: You can store it somewhere in static variable.

Sample code:

private static Clip clip;

public void keyReleased(KeyEvent e) {
    if (clip != null) {

public void playSound(File soundName) {        
        clip = AudioSystem.getClip();            
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download