+ 2

Best way to code in a sound file that I made.

I am trying to code in a sound file, that I create or will create, into a java program that I am writing. What is the best way import a library to handle that? And what is the code needed for that to play it at the proper time. I don’t want to have a sound player pop up, or if it does it is hidden. And the file will loop from that point until the program ends. Can anyone help with this? Thanks y’all!

30th Jun 2019, 5:52 PM
Tyler
4 Answers
+ 3
You could do something like this code to play the sound continuously until the program ends. I experimented with a .au file but ran into some unsupported format errors but the .wav format worked. SimpleAudioPlayer.java: import java.util.Scanner; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; public class SimpleAudioPlayer { private void sound() { try { AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getResource("maybe-next-time.wav")); Clip clip = AudioSystem.getClip(); clip.open(audioInputStream); clip.loop(Clip.LOOP_CONTINUOUSLY); // play infinitely. clip.start(); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) { new SimpleAudioPlayer().sound(); waitForUserInput(); } private static void waitForUserInput() { Scanner scanner = new Scanner(System.in); scanner.nextLine(); } } I want to give some credit to articles I copied that code from: - https://www.geeksforgeeks.org/play-audio-file-using-java/ - https://alvinalexander.com/java/java-audio-example-java-au-play-sound
30th Jun 2019, 11:44 PM
Josh Greig
Josh Greig - avatar
+ 2
If you have your .java files in a source directory, I'd add a "data" directory for the sound file(s). If your application can't find the file, just look at the FileNotFoundException's stack trace and edit the "getResource("maybe-next-time.wav")" until it works.
2nd Jul 2019, 1:11 AM
Josh Greig
Josh Greig - avatar
+ 1
i appreciate that, so my next question is where fo you store audio file? im using eclipse for this, so wiuld i need to create a folder or class that holds the audio file or .wav file?
1st Jul 2019, 4:12 PM
Tyler
+ 1
appreciate it man
2nd Jul 2019, 1:16 AM
Tyler