Can't figure out how to do Java Audio properly.

Those classes will just play the sound once or plays them in a loop.


// Load the clip
WavSound sound = WavPlayer.loadSound("shoot.wav");

// Play it once
sound.play();

// Play looping
sound.setLooping(true);
sound.play();

If you want to have effects, I think you can manipulate the data by getting the samples data and create a new WavSound object with the modified samples.

Hi packetpirate. I tried answering you earlier at StackOverflow.

According to this link, TinySound will support concurrent playbacks of Clips:

What exactly are you trying to load from the TinySound project? Can you point to the location of the zip file?

Have you done the whole shebang of “forking” “cloning” “pulling” to get a copy onto your desktop?

It’s easier for me to reply here than StackOverflow.

You need to build TinySound into a JAR yourself. Try creating a second project in NetBeans for TinySound, and copying all of the src folder contents from the zip file into it. You’ll probably have to link the JARs in the lib folder into that project to get it to build. Either compile a JAR from the new TinySound project and include it in your existing project, or you should be able to link the TinySound project as a library directly.

I’d seriously get your head around the Java build process and creating / using JARs before you try playing with sound further.

And really, really, really DO NOT use Clip :wink: . It’s implementation is not set up for doing what you want to do, or can end up working on one OS and not another.

Ok, I’ve implemented this, but now I have one other question about how to use it… for sounds that I want to loop, but to stop when certain things happen (ie: flamethrower sound loop until player stops firing the weapon), how would I do that?

EDIT: I suppose answering the previous question might give me an idea on how to solve this one, but this is also a huge problem… there is no delay between the fire() calls to the Flamethrower weapon (whose sound is the only one in the game that loops), so they all play together REALLY rapidly, and it comes out as a raucous jumble of noise.

The clip class has a loop and a stop method. But after you call stop the clip will get closed automatically so don’t call start or loop on it after you stopped it.
For a machine gun effect you need a delay. You probably have to create another Thread for that. You can communicate with that Thread through a volatile variable.

EDIT:
I updated my AudioData class


public class AudioData {
    private byte[] data;
    private AudioFormat format;
    private volatile boolean machineGunActive = false;
    private HashSet<Clip> clipsPlaying = new HashSet<>();
    
    private synchronized void removeClip(Clip clip) {
        clipsPlaying.remove(clip);
    }
    private synchronized void addClip(Clip clip) {
        clipsPlaying.add(clip);
    }
    private synchronized void stopAllClips() {
        for(Clip clip: clipsPlaying) clip.stop();
        clipsPlaying.clear();
    }
    
    AudioData(String fileName) {
       try {
           AudioInputStream sounds = AudioSystem.getAudioInputStream(AudioData.class.getResource(fileName));
           format = sounds.getFormat();
           int size = sounds.available();
           data = new byte[size];
           sounds.read(data);
           sounds.close();
       } catch(Exception e) {
           e.printStackTrace();
       }
    }
    public Clip createClip() {
        try {
            final Clip clip = AudioSystem.getClip();
            clip.addLineListener(new LineListener() {
             public void update(LineEvent e) {
                 LineEvent.Type type = e.getType();
                 if(type == type.STOP) {
                     clip.close();
                     removeClip(clip);
                 }
             }
            });
            clip.open(format, data, 0, data.length);
            return clip;
        } catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
    public void play() {
        Clip clip = createClip();
        addClip(clip);
        clip.start();
    }
    public void loop(int n) {
        Clip clip = createClip();
        addClip(clip);
        clip.loop(n);
    }
    public void loopForever() {
        Clip clip = createClip();
        addClip(clip);
        clip.loop(Clip.LOOP_CONTINUOUSLY);
    }
    public void stop() {
        machineGunActive = false;
        stopAllClips();
    }
    public void stopMachineGun() {
        machineGunActive = false;
    }
    public void playMachineGun(final int delay) {
        machineGunActive = true;
        new Thread() {
            public void run() {
                while(machineGunActive) {
                    play();
                    try {
                        Thread.sleep(delay);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}

Try this


AudioData data = new AudioData("shoot.wav");
data.playMachineGun(100);
Thread.sleep(2000);
data.stopMachineGun();

The difference between stop() and stopMachineGun() is that stop() will stop playing immediately, while stopMachineGun() allows the sound to fade out naturally.

Why would I need a delay? The sound is played when the fire() method is called on the gun, which already has a cooldown.
Anyway, I don’t think you get what I’m saying. Whereas most weapons in my game have a cooldown before they can be used again, the Flamethrower just fires particles continuously as long as the player holds down the fire button. The problem being that the sound is played when it’s fired, and since it’s being looped, that means dozens, or even hundreds, of the Flamethrower sound clip are being created and looped all at once. I tried making it so it wasn’t looped and just relied on the fire() event from the weapon to play the sound, but there are A LOT of particles coming out of this thing, so it still sounds like a machine gun of noise on crack. So what I’m asking is… how can I make it so the sound only plays if there is no Flamethrower sound currently being played? The play() method doesn’t return the clip that is generated to play the audio, so I can’t use that to determine if it’s running.

I thought of using a boolean, but how would I determine when the last clip generated by the play() method stops so I can generate a new one?

Wait, so you want to play the flamethrower sound only if it’s not playing anymore. Can’t you use loop()? Then it will automatically start playing again once it stopped.
Also, I edited my previous post. Take a look at the new code.

You’re missing the point. I already said that when it was looped, I couldn’t stop it because there is no way to stop the Clip once it has been created and started because that Clip only exists in the scope of the play() method in my sounds class. I would need access to that clip in my framework so I can call the stop() method on it under certain conditions. But simply returning the Clip from the play() method wouldn’t work because it would return to the weapon class. So unless I made a global variable for the Flamethrower Clip that changed whenever it’s played, which I think would be a hacky solution, but a bad idea, I can’t get it to stop when the player lets go of the fire button.

Also, forget the “machine gun”… that weapon is not the issue, and works just fine. It’s the Flamethrower that’s the problem, because there is no delay (or rather, only 20 ms delay) in between creation of each particle, which causes the sound to be played very rapidly, causing the noise in question.

EDIT: Just looked at your modified solution, and that MAY work, but I still feel as if there might be a better option. I’ll try it and get back to you.

If there is only a 20ms delay I guess it’s best to use loop(). And then call stop(), once the fire button has been released. You can do that by either making the flamethrower AudioData object globally accessible or by adding a MouseListener when the fire button is pressed. You can add as many MouseListeners to your game as you want. That listener will then stop the sound and remove itself.

Haha, oh wow… my new solution works perfectly for the Flamethrower, but now no other sounds will play… will I ever get this right?
Here’s the code I have now for the play() method in the AudioData class.


public void play(final double gain, final boolean smoothLoop) {
    final Clip clip = createClip();
    FloatControl gainControl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
    float dB = (float)(Math.log(gain) / Math.log(10.0) * 20.0);
    gainControl.setValue(dB);
    active = true;
    new Thread(new Runnable() {
        @Override
        public void run() {
            if(!smoothLoop) clip.start();
            else clip.loop(Clip.LOOP_CONTINUOUSLY);
            while(active) {
                if(!clip.isRunning() && !smoothLoop) active = false;
            }
            clip.stop();
        }
    }).start();
}

Basically, I had a boolean set on each AudioData called active that determines if the sound is currently playing. It’s set to true right before the clip starts playing. It then starts the clip and goes into a loop saying “if active, check to see if it’s running, and if it’s looped. If it’s no longer active and isn’t looped, set active to false”. This ensures that when a clip is finished with playback, it automatically sets active to false and then stops the clip. The looped parameter is provided by the Sounds class. So basically, for normal clips that aren’t looped, it sets active to true, then starts a thread in which it constantly checks that clip to see if it’s still running. If it’s no longer running, active is set to false, and then the clip stops. But for looped clips, like the Flamethrower, it will never set the active boolean to false, meaning it will continue to allow it to loop, never stopping. I then put in the setActive() method to set it to inactive when the mouse is released (among other conditions). So now the Flamethrower starts and stops like it’s supposed to, but none of the other clips even play.

What am I doing wrong?

EDIT: Nevermind, I just had to check if the clip was looped and only call stop() if it was looped.

But now you have an infinite loop that puts 100% load on one CPU core.
That’s what the LineListener is for. So you can react to the Clip stopping without needing a loop.
And as I already mentioned you can also use a MouseListener/KeyListener to react to buttons being pressed/released.

Also if you need an isRunning() method in the AudioData class you can define it like this


public synchronized boolean isRunning() {
    for(Clip clip: clipsPlaying) {
        if(clip.isRunning()) return true;
    }
    return false;
}

But I don’t think you even need that. AudioData has a stop method. Just call it when the button is released.

I don’t know how you think you get an infinite loop out of that. It’s working fine as it is right now.

If you loop a clip this code will run continuously until you set active to false.

while(active) {
    if(!clip.isRunning() && !smoothLoop) active = false;
}

Start a clip with smoothLoop set to true and then look at the Java program in your task manager. One of your CPU cores will have 100% load on it while the clip is playing.

Actually, I don’t use TinySound but I assume that you can use its JARs in Netbeans. In the project tab, select the “Libraries” node -> “Add JAR/Folder” and select all JARs.

Oh, come on! Just when I thought I was in the clear…

Everything works fine when I run the game through NetBeans, but when I Clean & Build it into a JAR and run it, all the sound in the game is cut short… like it only plays half the sound. What could be causing this in the JAR, but not in NetBeans?

You may find you will have some fun with computers running Linux, too, if computers running that OS matter to you.

I was about to respond and say the OP couldn’t find the JARs as per my previous message. Actually, there is a link to them on the GitHub page - assumed it was source only as GitHub deprecated downloads, but they’re still there at the moment.

http://finnkuusisto.github.com/TinySound/releases

To the OP, seriously, use a 3rd-party library like various people on here are suggesting. The way you’re using Clip may just about work on some operating systems, but where it does it’s not going to perform very well. Clip is just not designed / implemented in a useful way for this. You want a system that opens a line to the soundcard and keeps it open, mixing sounds in software - opening a line to the soundcard is not cheap. And neither are Threads. Some of the code on or linked to here is woefully inept - a Thread per sound, guys, seriously?! :emo:

I understand what you’re saying, but right now, I’d like to know why the sounds are being cut short when I run the JAR as opposed to the NetBeans Run Project button.
I may switch to TinySound after all, but first, I want to know what’s causing this.

Nobody? I really need to know why this is happening.

It has probably something to do with threads. Using threads incorrectly can cause all kinds of weird random errors.