Skip to content
Advertisement

How to get past using Deprecated API for audio in Java GUI game

So I’m coding a Java game and I want to add a sound effect when a certain point is reached. I have the sound effect in a .wav file in the same directory as the Java file itself.

I used one of the answers to this question: Best way to get Sound on Button Press for a Java Calculator? to get the audio playing – which it does completely fine (so my code works). However, the problem is that my compiler says that I am using or overriding a Deprecated API, and I am not sure if I want it to happen.

Here is the relevant code (which works but uses a deprecated API):

        String soundName = "NoGodNo.wav";    
        URL soundbyte = new File(soundName).toURI().toURL();
        java.applet.AudioClip clip = java.applet.Applet.newAudioClip(soundbyte);
        clip.play();

I did some research and found out that AudioClip was deprecated: https://docs.oracle.com/en/java/javase/11/docs/api/java.desktop/java/applet/AudioClip.html, and it has no replacement according to this link.

Is there a way to get past the Deprecated API message by replacing the code entirely? (Because AudioClip has no replacements).

Thanks in advance!

Advertisement

Answer

Never mind, I got it. Here’s the answer that DOESN’T use Deprecated APIs:

    try 
    {
        String soundName = "theme_audio.wav";    
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File(soundName).getAbsoluteFile());
        Clip clip = AudioSystem.getClip();
        clip.open(audioInputStream);
        clip.start();
    } catch (Exception e) {}

Thanks!

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement