Audio Not Playing

After about an hour of googling and trying a ton of different code samples I finally managed to get to the below code which has no errors but it also doesn’t play the audio file; if anyone can see what I’ve done wrong that’ll help.

package Core;

import java.io.InputStream;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;


public class AudioHandler
{
   public AudioHandler()
   {
        InputStream in;
        AudioStream as;
        try 
        {
            in = this.getClass().getClassLoader().getResourceAsStream("Resources/Sound/grenade.wav");
            as = new AudioStream(in);
            AudioPlayer.player.start(as);
        }
        catch (Exception e)
        { 
            e.printStackTrace();
        }
   }
}

Most of the other code samples either wouldn’t work with a URL path or they had this weird error “javax.sound.sampled.LineUnavailableException”. So I ended up smashing a bunch of things together to make the above; it doesn’t show any errors at all when compiling/running so I have no idea what could be wrong.

Never use JavaAudio. Not ever.
Try easyogg / jogg / jorbis

You shouldn’t use the “sun.*” packages as they are intended for internal use only and subject to change.

JavaSound is all around a hellish experience. If you want audio, you could use TinySound:

Paul’s 3D Sound System is another option. Generally speaking, anything based on OpenAL will be better and more reliable than JavaSound.

I just figured out how to use TinySound and after a little bit of messing around with the example code I got the sound to play. The sound did play properly but only if the code was like this:

public AudioHandler()
   {
        //initialize TinySound
		TinySound.init();
		//load a sound and music
		//note: you can also load with Files, URLs and InputStreams
                URL url = this.getClass().getClassLoader().getResource("Resources/Sound/grenade.wav");
		Sound grenade = TinySound.loadSound(url);
                grenade.play();
   }

It would not play if I had ‘TinySound.shutdown();’ at the end. Is there some way to delay the execution of the code until the sound has finished playing so that TinySound isn’t shut down until the sound has finished playing?

TinySound should replace the garbage that Java currently comes with.

Generally your game loops should be written like this:

public void loop() {
    .. initialize resources ..    

    while ( running ) {
        .. update and render game ..
    }

    .. destroy resources ..
}

So you would initialize TinySound before your loop and load/play any sounds. If, say, a user clicks a button while the game is running, you may choose to play the sounds again. Then, at the end of the game, when the user is quitting and the game loop is finished running, you would destroy TinySound and let it consume any resources.

Why would your thought process be like this, shutting down what you seek to create in the end of the constructor?