Created
January 13, 2019 00:26
-
-
Save ny83427/9285b75706a8024e7b50f99645c6c470 to your computer and use it in GitHub Desktop.
Play java audio file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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