Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Play java audio file
/**
* Initialize JFX toolkit if you are not running in JavaFX GUI environment
* It supports mp3, wav and is much easier to use
*/
void cheer() {
PlatformImpl.startup(() -> {
Media hit = new Media(new File("audios/cheer.mp3").toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(hit);
mediaPlayer.play();
});
}
/**
* Many restrictions and don't suggest to use, though it would work
*/
void cheerWithoutJFX() {
SourceDataLine dataLine = null;
try {
final File file = new File("audios/welcome.wav");
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
AudioFormat format = ais.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
dataLine = (SourceDataLine) AudioSystem.getLine(info);
dataLine.open(format);
dataLine.start();
int bytesRead = 0;
byte[] bytes = new byte[dataLine.getBufferSize()];
while (bytesRead != -1) {
bytesRead = ais.read(bytes, 0, bytes.length);
if (bytesRead >= 0) {
dataLine.write(bytes, 0, bytesRead);
}
}
} catch (UnsupportedAudioFileException | LineUnavailableException | IOException e) {
e.printStackTrace();
} finally {
if (dataLine != null) {
dataLine.drain();
dataLine.stop();
dataLine.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.