final/src/SoundWrapper.java

60 lines
2.0 KiB
Java

import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.*;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.*;
public class SoundWrapper implements Serializable {
transient public Sound sound;
public String soundString;
public static Sound grass;
static {
try {
grass = new Sound("sound/grass.wav");
} catch (UnsupportedAudioFileException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (LineUnavailableException e) {
throw new RuntimeException(e);
}
}
// please note that not as many constructors were implemented as BufferedImage, as this class was created before most sounds were added;
// as such, backwards compatibility was not needed
public SoundWrapper(String soundLocation) throws UnsupportedAudioFileException, LineUnavailableException, IOException {
sound = new Sound(soundLocation);
soundString = soundLocation;
}
public SoundWrapper() {}
@Serial
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(soundString);
}
@Serial
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException, UnsupportedAudioFileException, LineUnavailableException {
Object o;
o = in.readObject();
sound = new Sound((String)o);
}
public static void playSound(String filePath) throws UnsupportedAudioFileException, LineUnavailableException, IOException {
Sound sound = new Sound(filePath);
if (sound == null) {
try {
sound = new Sound(filePath);
} catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) {
throw new RuntimeException(e);
}
}
sound.start();
}
}