Adding Music To Java - java

I'm making connect four for my high school cpt and I'm trying to add music to the background and for sound effects. My teacher gave me some code to work with, but since I have never worked with sound I don't understand how to use it. Can someone please explain the code that I was given? Thanks for your help!
try {
AudioInputStream audio = AudioSystem.getAudioInputStream(new File("SoundFile.wav"));//use wav. mp3 doesn't work
Clip clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
}
catch(UnsupportedAudioFileException uae) {
System.out.println(uae);
}
catch(IOException ioe) {
System.out.println(ioe);
}
catch(LineUnavailableException lua) {
System.out.println(lua);
}

You need to import the following classes from the relevant packages:
AudioInputStream
UnsupportedAudioFileException
IOException
LineUnavailableException
File

Related

Needing to type full path to save file?

Okay, this is my first post here, sorry if i did something wrong. (please let me know if i did aswell)
So i've been trying to make a "data" folder with a audio(.wav) file in it when the runnable jar file is run but for some reason it doesn't work, i've tried to get this working for the last week but i finally kinda gave up on trying to get it working without help(other than searching around the internet) and therefore ask here.
So i have this code:
public static void loop(String path, int volume) {
try {
if (volume > 6) throw new IllegalArgumentException("Requested volume ("+volume+") is higher than allowed. (maximum 6)");
else if (volume < -80) throw new IllegalArgumentException("Requested volume ("+volume+") is lower than allowed. (minimum -80)");
else {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File(path)));
clip.loop(Clip.LOOP_CONTINUOUSLY);
FloatControl gain = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gain.setValue(volume);
clip.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
for looping a .wav file continuously and it works, then i try to save the file with this code:
public void save(String music, String output) {
try {
File sound = new File(music);
AudioInputStream ais = AudioSystem.getAudioInputStream(sound);
AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new File(output));
} catch (IOException | UnsupportedAudioFileException e) {
e.printStackTrace();
}
}
And that seems to work aswell when i do something like this:
save("D:\\Eclipse\\eclipse\\workspace\\Test\\data\\music.wav", "C:\\Users\\Karim\\Desktop\\data\\test.wav");
loop("C:\\Users\\Karim\\Desktop\\data\\test.wav", -30);
But if i try to do this instead:
private File jar() {
try {
File jar = new File(Game.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
return jar;
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
private File data = new File(jar().getParentFile().getPath()+File.separator+"\\data");
private File music = new File(data.getPath()+"\\music.wav");
save(music.getPath(), "C:\\Users\\Karim\\Desktop\\data\\test.wav");
loop("C:\\Users\\Karim\\Desktop\\data\\test.wav", -30);
it won't save the file, why is that and what can i do to make it save?
Final Notes:
I'm pretty new to java.
I'm pretty new to programming in itself.
I don't want to use a library, i wanna try to make it work without and i'm so close.
If i forgot to say anything please let me know and i'll edit this post or make a comment.
EDIT: Just wanted to make it clear that this works in the IDE but not when i export it. Also i have the data folder both IN the 'src' folder and beside the 'src' folder, just for testing.

.wav sounds not playing in Java

I am currently using this function to play .WAV files
public void playSound(String sound){
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource(sound);
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
The problem is that no sound is being played when I call the function on a file, no errors or exceptions are thrown or whatsoever the program just starts and stops, no sound plays, I tried with a lot of different .WAV files with no success.
The programm stops before it has time to play the sound since start is non-blocking.
Try the following :
clip.start();
clip.drain();
clip.close();
This works for me:
public void sound() {
try{
AudioInputStream ais = AudioSystem.getAudioInputStream(new File("./sounds/player-laser.wav"));
Clip test = AudioSystem.getClip();
test.open(ais);
test.loop(0);
}catch(Exception ex){
ex.printStackTrace();
}
}

How to give path of the music file that is inside the Java package?

I created a package named sounds in my Java project and my sound is in this package. However, I get an java.io.FileNotFoundException error with this code. So how can I give the path of this file?
path="sounds/hit.wav"
path is given like above
public class Sound {
AudioInputStream audio;
Clip clip;
//String path;
public void play(String path)
{
try{
File soundFile =new File(path);
audio = AudioSystem.getAudioInputStream(soundFile);
clip = AudioSystem.getClip();
clip.open(audio);
clip.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I also tried this one and it gives an IOException:
clip.open(AudioSystem.getAudioInputStream(
new BufferedInputStream(getClass().getResourceAsStream("/sounds/hit.wav"))));
Can you please tell me how can I solve this problem?
Here is my file structure:
URL urlToHit = this.getClass().getResource("/edu/iyte/ceng316/resource/hit.wav");
System.out.println(urlToHot);
Maybe:
clip.open(AudioSystem.getAudioInputStream(getClass().getResourceAsStream("sounds/hit.wav"));

No sound after export to jar

I have problem with my app. When I run app in Eclipse, sound played well, but if I export app to runnable jar, sound doesn't work.
Method, where sound is played:
public static synchronized void playSound()
{
new Thread(new Runnable()
{
// The wrapper thread is unnecessary, unless it blocks on the
// Clip finishing; see comments.
public void run()
{
try
{
Clip clip = AudioSystem.getClip();
AudioInputStream inputStream = AudioSystem.getAudioInputStream(getClass().getResourceAsStream("sound.wav"));
clip = AudioSystem.getClip();
clip.open(inputStream);
clip.start();
}
catch (Exception e)
{
System.err.println(e.getMessage());
}
}
}).start();
}
Where can be a mistake?
The problem is in this
AudioInputStream inputStream = AudioSystem.getAudioInputStream(getClass().getResourceAsStream("sound.wav"));
in JAR file isn't working getResourceAsStream for any reason. So I replace it with getResource:
AudioInputStream inputStream = AudioSystem.getAudioInputStream(getClass().getResource("sound.wav"));
and this works fine.

Java Sound Repeated Play

I'm trying to add sound to a game I've been working on, and I'm having trouble getting the sounds to play more than once. I think I've worked out the cause, but I'm not sure how to solve it. I'm using an enumerator I found while searching for a Java sound tutorial.
The problem is that I'm calling the sound within a thread, in my update() method, and that each time I call the play() method of the sound, it starts the clip over. The first time it's called, the sound plays fine (I may get a bit of a freeze), but all attempts afterwards to play the sound fail. I don't get any exceptions or errors, the sound just doesn't play.
public enum Sounds {
RIFLE("rifle_fire.wav");
private Clip clip;
Sounds(String filename) {
openClip(filename);
}
public synchronized void openClip(String filename) {
try {
URL audioFile = Sounds.class.getResource("/resources/sounds/" + filename);
AudioInputStream audio = AudioSystem.getAudioInputStream(audioFile);
AudioFormat format = audio.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(audio);
} catch (UnsupportedAudioFileException uae) {
System.out.println(uae);
} catch (IOException ioe) {
System.out.println(ioe);
} catch (LineUnavailableException lue) {
System.out.println(lue);
}
}
public synchronized void play() {
if(clip.isRunning()) clip.stop();
clip.setFramePosition(0);
clip.start();
}
public static void init() {
values();
}
}
That is the enumerator I use. It's called from the update() method of my main thread, which is updated every 20 ms. In the update method, I call it like this.
// If the left mouse button is held down, create a new projectile.
if(Globals.buttons[0] && !player.isOnCooldown()) {
createParticle(pAngle);
Sounds.RIFLE.play();
}
Someone suggested I need to close the line after using it, but the sound is only opened once... why would I need to close it? Anyone know what the problem is?

Categories