Home > Software engineering >  In Java, how can I play a sound for a given period?
In Java, how can I play a sound for a given period?

Time:12-25

My target is to play a given sound or music for a given second, but the music file is actually longer than the given seconds. i.e. the file is 2 min 32 seconds long but only required to play 16 seconds. My design of player part is:

public class MusicClip {
    private Clip clip;
    private Long pos;
    
    private String status;
    private String pathKeeper;
    
    private AudioInputStream AIS = null;
    
    public MusicClip(String path) throws LineUnavailableException, UnsupportedAudioFileException, IOException {
        AIS = AudioSystem.getAudioInputStream(new File(path));
        pathKeeper = path;
        clip = AudioSystem.getClip();
        clip.open(AIS);
        status = "waiting";
    }
    
    public void play() 
    { 
        if (status.equals("play")) 
        { 
            System.out.println("audio is already playing"); 
            return; 
        } 
        //start the clip 
        clip.start(); 
        status = "play"; 
    } 

    public void stop() { 
        pos = 0L; 
        clip.stop(); 
        clip.close();
        status = "waiting";
    } 
    
    //restart the clip in case to replay
    public void resetAudioStream() {
        try {
            AIS = AudioSystem.getAudioInputStream(new File(pathKeeper));
            clip.open(AIS);
        } catch (Exception e) {
            //This shouldn't happen!
            System.err.println("OOPS!");
        }
        status = "waiting";
    } 

The first thing that comes to my mind is timer but I don't understand how it is implemented. Are there any approaches or solutions with timer or other ways?

CodePudding user response:

Theoretically, if I understand the question right, you can just call stop() after x seconds when you call play()

new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            stop();
        }
    }, TimeUnit.SECONDS.toMillis(3));
  •  Tags:  
  • java
  • Related