Sound problems in Java

后端 未结 1 2009
南笙
南笙 2021-01-21 22:29

I have some questions about playing sound in Java and I hope you can help me out.
1. How can I stop a playing sound with a \"Stop\" button?
2. How can I slow down (or co

相关标签:
1条回答
  • 2021-01-21 22:59

    You're working in an Object Oriented programming lanuage, so let's take advantage of that and encapsulate the management of the clip/audio into a simple class...

    public class AudioPlayer {
    
        private Clip clip;
    
        public AudioPlayer(URL url) throws IOException, LineUnavailableException, UnsupportedAudioFileException {
            clip = AudioSystem.getClip();
            clip.open(AudioSystem.getAudioInputStream(url.openStream()));
        }
    
        public boolean isPlaying() {
            return clip != null && clip.isRunning();
        }
    
        public void play() {
            if (clip != null && !clip.isRunning()) {
                clip.start();
            }
        }
    
        public void stop() {
            if (clip != null && clip.isRunning()) {
                clip.stop();
            }
        }
    
        public void dispose() {
            try {
                clip.close();
            } finally {
                clip = null;
            }
        }
    
    }
    

    Now, to use it, you need to create a class instance field which will allow you to access the value from anywhere within the class you want to use it...

    private AudioPlayer bgmPlayer;
    

    Then, when you need it, you create an instance of AudioPlayer and assign it to this variable

    try {
        bgmPlayer = new AudioPlayer(getClass().getResource("/BGM.wav"));
    } catch (IOException | LineUnavailableException | UnsupportedAudioFileException ex) {
        ex.printStackTrace();
    }
    

    Now, when you need to, you simply call bgmPlayer.play() or bgmPlayer.stop()

    0 讨论(0)
提交回复
热议问题