Skip to content

Instantly share code, notes, and snippets.

@ny83427
Created January 13, 2019 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ny83427/9285b75706a8024e7b50f99645c6c470 to your computer and use it in GitHub Desktop.
Save ny83427/9285b75706a8024e7b50f99645c6c470 to your computer and use it in GitHub Desktop.
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