Stop method not working

Posted by avoq on Stack Overflow See other posts from Stack Overflow or by avoq
Published on 2010-04-18T20:59:16Z Indexed on 2010/04/18 21:03 UTC
Read the original article Hit count: 339

Filed under:

Hi everyone , can anybody tell me why the following code doesn't work properly? I want to play and stop an audio file. I can do the playback but whenever I click the stop button nothing happens. Here's the code : Thank you.

..................

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

public class SoundClipTest extends JFrame {

final JButton button1 = new JButton("Play");
final JButton button2 = new JButton("Stop");
int stopPlayback = 0;  

// Constructor public SoundClipTest() {

  button1.setEnabled(true);
  button2.setEnabled(false);

  // button play
  button1.addActionListener( 
 new ActionListener(){

 public void actionPerformed(ActionEvent e){

 button1.setEnabled(false);
 button2.setEnabled(true);

  play();
    }// end actionPerformed

  }// end ActionListener

);// end addActionListener()          


 // button stop
button2.addActionListener(
new ActionListener(){
public void actionPerformed(
ActionEvent e){
      //Terminate playback before EOF

 stopPlayback = 1;



    }//end actionPerformed
  }//end ActionListener
);//end addActionListener()


  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setTitle("Test Sound Clip");
  this.setSize(300, 200);
  JToolBar bar = new JToolBar();
  bar.add(button1);
  bar.add(button2);
  bar.setOrientation(JToolBar.VERTICAL); 
  add("North", bar);
  add("West", bar);
  setVisible(true);

}  

 void play() { 



  try {

final File inputAudio = new File("first.wav");
// First, we get the format of the input file
final AudioFileFormat.Type fileType = AudioSystem.getAudioFileFormat(inputAudio).getType();
// Then, we get a clip for playing the audio.
final Clip c = AudioSystem.getClip();
// We get a stream for playing the input file.
AudioInputStream ais = AudioSystem.getAudioInputStream(inputAudio);
// We use the clip to open (but not start) the input stream
c.open(ais);
// We get the format of the audio codec (not the file format we got above)
final AudioFormat audioFormat = ais.getFormat();



c.start();
if  (stopPlayback == 1 ) {c.stop();}  



} catch (UnsupportedAudioFileException e) {
     e.printStackTrace();
  } catch (IOException e) {
     e.printStackTrace();
  } catch (LineUnavailableException e) {
     e.printStackTrace();

           }

}// end play

public static void main(String[] args) { //new SoundClipTest().play(); new SoundClipTest(); } }

© Stack Overflow or respective owner

Related posts about java