From 41c5da9fb7598503b1af0c39c92611771920071e Mon Sep 17 00:00:00 2001 From: peam8y43l <3421917108@qq.com> Date: Sat, 13 Apr 2024 20:47:33 +0800 Subject: [PATCH] =?UTF-8?q?=E9=9F=B3=E4=B9=90=E6=92=AD=E6=94=BE=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/SoundPlayer.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/SoundPlayer.java diff --git a/src/SoundPlayer.java b/src/SoundPlayer.java new file mode 100644 index 0000000..1bb19c7 --- /dev/null +++ b/src/SoundPlayer.java @@ -0,0 +1,34 @@ +package impl; + +import javax.sound.sampled.*; +import java.io.File; +import java.io.IOException; + +public class SoundPlayer { + private Clip clip; + + public SoundPlayer(String filePath) { + try { + File soundFile = new File(filePath); + AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(soundFile); + clip = AudioSystem.getClip(); + clip.open(audioInputStream); + } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) { + e.printStackTrace(); + } + } + + public void play() { + if (clip != null) { + clip.setFramePosition(0); // Rewind to the beginning + clip.start(); + } + } + + public void stop() { + if (clip != null && clip.isRunning()) { + clip.stop(); + } + } + +} \ No newline at end of file