简体   繁体   中英

Repeated audio clip not playing - Java

I have a scheduled thread that runs every half-second or so and plays an audio clip each time, calling stop() on the clip before each cycle in order to start() it again:

public AudioThread() {
    Clip clipF5 = AudioSystem.getClip();
    AudioInputStream inputF5 = AudioSystem.getAudioInputStream(Main.class.getResourceAsStream("sound.wav"));
    clipF5.open(inputF5);
}

ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();

exec.scheduleAtFixedRate(new Runnable() {
    public void run() {
        if (clipF5.isRunning()) { clipF5.stop(); }

        clipF5.start();
    }
}, 1, interval, TimeUnit.MICROSECONDS);

But it doesn't play again after the first time. The code runs, but the sound doesn't play. Any ideas?

You have to re-engineer your solution. Here's the solution I'm proposing:

public void audioThread() {
  try {
    Clip clipF5 = AudioSystem.getClip();

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();

    exec.scheduleAtFixedRate(new Runnable() {
    public void run() {
      try {    
        AudioInputStream inputF5 = AudioSystem.getAudioInputStream(new File("1.wav"));
        clipF5.close();
        clipF5.open(inputF5);
        clipF5.start();
      }
      catch(Exception eg) { eg.printStackTrace(); }
    }
    }, 1, 10000000, TimeUnit.MICROSECONDS);
  }
  catch(Exception eg) { eg.printStackTrace(); }
}

This will start every 10 seconds from the beginning of the song.

Easy to fix!

You just need to add the step of resetting the media position. You can do this with either clip.setFramePosition(0) or clip.setMicrosecondPosition(0) to go back to the beginning of the clip. The start() method simply starts from the last media position, even if it is the end of the file.

if (clipF5.isRunning()) 
{
    clipF5.stop(); 
    clipF5.setFramePosition(0);
}

clipF5.start();

I'm assuming the length of your clip is less than 30 seconds!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM