0

I have code that plays sound from a .wav file, but I have no way of stopping the song, or even quitting the program until it ends. As this is a 5 minute song, this is a problem. Here is the code for how I play the wav:

public class EasySound{
   private SourceDataLine line = null;
   private byte[] audioBytes;
   private int numBytes;

   public EasySound(String fileName){
      File  soundFile = new File(fileName);
   AudioInputStream audioInputStream = null;
   try {
     audioInputStream = AudioSystem.getAudioInputStream(soundFile);
   } catch (Exception ex) {
   System.out.println("*** Cannot find " + fileName + " ***");
   System.exit(1);
   }

   AudioFormat audioFormat = audioInputStream.getFormat();
   DataLine.Info info = new DataLine.Info(SourceDataLine.class,
                     audioFormat);
   try {
   line = (SourceDataLine)AudioSystem.getLine(info);
   line.open(audioFormat);
   } catch (LineUnavailableException ex) {
   System.out.println("*** Audio line unavailable ***");
   System.exit(1);
   }

   line.start();

   audioBytes = new byte[(int)soundFile.length()];

   try {
   numBytes = audioInputStream.read(audioBytes, 0, audioBytes.length);
   } catch (IOException ex) {
     System.out.println("*** Cannot read " + fileName + " ***");
     System.exit(1);
   }
 }

 public void play() {
line.write(audioBytes, 0, numBytes);
 }

 }

Is there a better way to do this, or a way to do this that would allow me to stop the song mid-play?

Thanks in advance!

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
dawsonc
  • 25
  • 3

1 Answers1

0

Play the audio file in a separate thread. Keep the UI in a different thread that has access to the "play" thread. When the user wants to pause, you can simply pause that thread. I would be surprised if whatever library you are using does not have a feature like this though....

thatidiotguy
  • 8,701
  • 13
  • 60
  • 105
  • I got the library from a friend, who wrote it to play beeps, which take like half a second to play. The problem only comes up when I try to play something longer. Thanks for the response! – dawsonc Sep 19 '12 at 23:00