Search code examples
javaaudiomilliseconds

How to play a sound in java from the millisecond X


I have a problem, I wanna play a sound (or music file) for example from the second 10 to the 12, it is possible to make an function like soundObject.play(10000,12000); ? actually i'm testing sound classes but I only can play, stop and loop

Thank you!


Solution

  • I finally found the answer, this is the code I used to play the 3-5 seconds

    import java.io.IOException;
    import java.net.URL;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.UnsupportedAudioFileException;
    
    public class SoundClipTest{
    
       public static void main(String[] args) throws UnsupportedAudioFileException, IOException, LineUnavailableException {
           URL myURL= ClassLoader.getSystemResource("abesti.wav");
           AudioInputStream audio = AudioSystem.getAudioInputStream(myURL);
           Clip clip = AudioSystem.getClip();
           clip.open(audio);
           clip.setMicrosecondPosition(3000000);
           clip.start();
           try {
            Thread.sleep(2000); //in milliseconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
           clip.stop();
       }
    }