|
| 1 | +package com.redomar.game.audio; |
| 2 | + |
| 3 | +import javax.sound.sampled.AudioFormat; |
| 4 | +import javax.sound.sampled.AudioInputStream; |
| 5 | +import javax.sound.sampled.AudioSystem; |
| 6 | +import javax.sound.sampled.Clip; |
| 7 | + |
| 8 | + |
| 9 | +public class AudioHandler { |
| 10 | + |
| 11 | + private Clip clip; |
| 12 | + |
| 13 | + public AudioHandler(String path){ |
| 14 | + try{ |
| 15 | + AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(getClass().getResourceAsStream(path)); |
| 16 | + AudioFormat baseformat = audioInputStream.getFormat(); |
| 17 | + AudioFormat decodeFormat = new AudioFormat( |
| 18 | + AudioFormat.Encoding.PCM_SIGNED, |
| 19 | + baseformat.getSampleRate(), 16, |
| 20 | + baseformat.getChannels(), |
| 21 | + baseformat.getChannels() * 2, |
| 22 | + baseformat.getSampleRate(), |
| 23 | + false |
| 24 | + ); |
| 25 | + AudioInputStream decodedAudioInputStream = AudioSystem.getAudioInputStream( |
| 26 | + decodeFormat, audioInputStream); |
| 27 | + clip = AudioSystem.getClip(); |
| 28 | + clip.open(decodedAudioInputStream); |
| 29 | + } catch (Exception e){ |
| 30 | + System.err.println(e.getStackTrace()); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + public void play(){ |
| 35 | + if(clip == null) return; |
| 36 | + stop(); |
| 37 | + clip.setFramePosition(0); |
| 38 | + clip.start(); |
| 39 | + } |
| 40 | + |
| 41 | + public void stop() { |
| 42 | + if (clip.isRunning()) clip.stop(); |
| 43 | + } |
| 44 | + |
| 45 | + public void close(){ |
| 46 | + stop(); |
| 47 | + clip.close(); |
| 48 | + } |
| 49 | + |
| 50 | +} |
0 commit comments