0

I am trying to create a simple program and in this program, I have managed to load sprite assets from a library class folder named 'res'. I got to a point where I wanted to add music into the program but just as it happened with images it wouldn't work unless I accessed it from a resource class folder.

On the internet, I couldn't find anything about accessing and playing audio files from this folder as I had with images. Is it possible to play music from these folders, and if so, how?

This is how I accessed my images:

package sbg.firstgame.gfx;

import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageLoader {
public static BufferedImage loadImage(String path){
    try {
        return ImageIO.read(ImageLoader.class.getResource(path));
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
        return null;
    }
}

That's the image code and if it could be similar to that, it would be awesome. Thanks for the help.

1 Answers1

-1
import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class AudioPlayer {
    public static void playAudio() {
        AudioInputStream audioIn;
        try {
            audioIn = AudioSystem.getAudioInputStream(AudioPlayer.class.getResourceAsStream("/audio/file.wav"));
            Clip clip = AudioSystem.getClip();
            clip.open(audioIn);
            clip.start();
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException  e) {
            e.printStackTrace();
        }
    }

}

This works with only javax libs. But there are many ways to do it.

Here is an example for a quick audio player implementation https://www.geeksforgeeks.org/play-audio-file-using-java/

Nils K
  • 44
  • 6