简体   繁体   中英

Is there a way to stop an audio clip playing in the middle of the clip?

I am developing an alarm clock program that plays an audio clip as an alarm. I can successfully play an audio clip, and terminate an inactive alarm. However, when I try to terminate an alarm that is currently playing, the audio keeps playing. Solutions I've tried were setting the clip to null, clip.stop(); and

public void stopSound(Clip clip){
    clip.stop();
    clip.flush();
    clip.close();
}

Is there a way to end a clip at any percentage through a clip?

This works for me. It stops after 5 seconds of playing.

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args) {
        playMusic("<Type your path to music here>");
    }


    static void playMusic(String musicLocation) {
        new Thread(() -> {
            try {
                File musicPath = new File(musicLocation);
                if (musicPath.exists()) {
                    AudioInputStream audioInput = AudioSystem.getAudioInputStream(musicPath);
                    Clip clip = AudioSystem.getClip();
                    clip.open(audioInput);
                    clip.start();

                    TimeUnit.SECONDS.sleep(5);

                    clip.stop();
                } else {
                    System.out.println("Can't find file");
                }
            } catch (IOException | UnsupportedAudioFileException | LineUnavailableException | InterruptedException e) {
                throw new RuntimeException(e);
            }
        }).start();
    }
}

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