com.arch.util.WavUtils Maven / Gradle / Ivy
package com.arch.util;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;
import java.io.InputStream;
public final class WavUtils {
private WavUtils() {
}
public static boolean playUnique(final InputStream arquivo) {
return play(arquivo, 0);
}
public static boolean playRepeat(final InputStream arquivo) {
return play(arquivo, Clip.LOOP_CONTINUOUSLY);
}
private static boolean play(final InputStream arquivo, int count) {
try (final AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(arquivo)) {
// Carrega o formato do audio e cria uma linha
final AudioFormat audioFormat = audioInputStream.getFormat();
final DataLine.Info dataLineInfo = new DataLine.Info(Clip.class,
audioInputStream.getFormat(),
(int) audioInputStream.getFrameLength() * audioFormat.getFrameSize());
// Carrega o som para o dispositivo
try (final Clip clip = (Clip) AudioSystem.getLine(dataLineInfo)) {
// Evento do LineListener
clip.addLineListener(e -> {
if (LineEvent.Type.STOP.equals(e.getType())) {
e.getLine().close();
}
});
clip.open(audioInputStream);
clip.loop(count);
}
return true;
} catch (LineUnavailableException | UnsupportedAudioFileException | IOException e) {
LogUtils.generate(e);
return false;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy