javaubuntuwavjavasound

Java sound replaying via Clip and AudioInputStream is not working


This is a slightly modified example from the Java Sound info page. https://stackoverflow.com/tags/javasound/info Unfortunately, it only plays the sound once but the intention is twice.

import java.io.File;
import javax.sound.sampled.*;

public class TestNoise {
    public static void main(String[] args) throws Exception {
        File f = new File("/home/brian/drip.wav");
        AudioInputStream ais = AudioSystem.getAudioInputStream(f);

        AudioFormat af = ais.getFormat();
        DataLine.Info info = new DataLine.Info(Clip.class, af);
        Clip clip = (Clip)AudioSystem.getLine(info);

        clip.open(ais);
        clip.start();    // heard this
        Java.killTime(); 
        clip.start();    // NOT HEARD
        Java.killTime();
    }
}

Edit: To understand the answer, see the link provided by Wanderlust or just do what it says in the comment below his answer.


Solution

  • For playing the clip for the second time you must call

    clip.start();
    clip.stop();
    

    cause after the second call of clip.start(); it is trying to play the file from the place where it stopped previously.