Bill Darson
Bill Darson

Reputation: 23

While loop not working In audio player

I'm using a sound player and I'm trying to create a while loop that knows when to terminate the JFrame it's playing in. The while loop should loop while the clip (recording) is playing and end when the clip is done. But here's the deal: The while loop only works when it prints something out, which I DON'T want it to do?

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

public class SoundClipTest extends JFrame {

public SoundClipTest() {
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  try {
     // Open an audio input stream.
    File soundFile = new File("Testing/recording (2).wav");
    AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
    //URL url = new URL("http://maximumdonline.com/miscwavs/pacman.wav");
    //AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
     // Get a sound clip resource.
     Clip clip = AudioSystem.getClip();

     // Open audio clip and load samples from the audio input stream.
     clip.open(audioIn);
     clip.start();
     this.setVisible(true);
     this.setVisible(false);
     boolean run = true;

     //problem While Loop
     while(clip.isActive()){
          //Only works when I print something out during the loop:
         //System.out.println(run);

     }
     //Test While Loop has ended.
     run = false;
     System.out.println(run);
     //Close JFrame
  } catch (UnsupportedAudioFileException e) {
     e.printStackTrace();
  } catch (IOException e) {
     e.printStackTrace();
  } catch (LineUnavailableException e) {
     e.printStackTrace();
  }
}

Note: Most of this sound code came from https://www.ntu.edu.sg/home/ehchua/programming/java/J8c_PlayingSound.html It works. I've tested it, but my while loop is crying!

Upvotes: 0

Views: 139

Answers (2)

Garun
Garun

Reputation: 22

Try modifying your code to

while (clip.isActive()) { if(!clip.isRunning()) clip.stop(); }

This did the trick for me

Upvotes: -1

Andrew Thompson
Andrew Thompson

Reputation: 168845

The correct way to approach this task is to add a LineListener to the Clip. A Clip implements javax.sound.sampled.Line interface, so we can use Line.addLineListener(LineListener)..

Adds a listener to this line. Whenever the line's status changes, the listener's update() method is called with a LineEvent object that describes the change.

Upvotes: 3

Related Questions