audio1.java

This example combines features from the first two examples (1   2). It demonstrates how a sound clip can be played multiple times, first by using a JButton (this code) and then by using a for loop (audio2.java)


audio1.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.sound.sampled.*;
import java.io.*;
import java.net.URL;



class audio1 implements LineListener{

   public Clip clip;
   boolean playCompleted;

   audio1(String filename) {
	open(filename);

   }

   public void open(String filename) {
     try{
          URL url = getClass().getClassLoader().getResource(filename);
         AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
	 AudioFormat audioFormat = audioIn.getFormat();

         DataLine.Info info = new DataLine.Info(Clip.class, audioFormat);
 
         // Get a sound clip resource.
         clip = AudioSystem.getClip();
	clip.addLineListener(this);
         // Open audio clip and load samples from the audio input stream.
         clip.open(audioIn);
        }catch(Exception e)
        {
        System.err.println(e);
        }
   }

   public void play() {
           clip.start();
	   playCompleted = false;
            int count=0; 
            while (!playCompleted) {
                // wait for the playback completes
                try {
                    Thread.sleep(100);
		    count++;
                } catch (InterruptedException ex) {
                    System.err.println(ex.getMessage());
                }
            }
	    //System.out.println("ellapsed time " + count + " tenth seconds");
    }

    /**
     * Listens to the START and STOP events of the audio line.
     */
    @Override
    public void update(LineEvent event) {
        LineEvent.Type type = event.getType();
         
        if (type == LineEvent.Type.START) {
            //System.out.println("Playback started.");
	    playCompleted = false;             
        } else if (type == LineEvent.Type.STOP) {
            //System.out.println("Playback completed.");
	    playCompleted = true;
	    clip.setFramePosition(0);
        }
 
    }


   public static void main(String[] args) {

	 audio1 aud = new audio1("cuckoo.wav");
	 JButton button = new JButton("ding");
 	 button.addActionListener(ae -> aud.play());
 
     EventQueue.invokeLater(()-> {
      	 JFrame win = new JFrame("audio1");
	 JPanel panel = new JPanel();
	 panel.add(button);	win.add(panel);
	win.add(panel, BorderLayout.NORTH);
	 win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	win.setSize(196,140);
	//win.pack();
	win.setLocationRelativeTo(null);  // Center window.
	 win.setVisible(true);
       });

   }

}


Maintained by John Loomis, updated Thu May 07 16:03:27 2020