What audio format should I use for java?

25.7k views Asked by At

I am making a Java based game for which I want to add some sound effects. I searched and found myself more confused. I know the coding differs from file format to format. I just need some sounds - does not matter which format. So please suggest me the easiest file format. Code snippet will be extremely helpful.

What is the easiest format and way to provide sound effects?

5

There are 5 answers

0
Basilio German On BEST ANSWER

for short sounds, you should use WAV or AU, WAV being the most known format for small sounds. i just finished this small program, all you need to do is have a .wav sound.

this program spawns a window with a button and every time you click that button the specified sound will play.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;

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;
import javax.swing.JButton;
import javax.swing.JFrame;

public class PlaySound extends JFrame{

    private Clip clip;

    public static void main(String [] args) {

        PlaySound app = new PlaySound();

    }

    public PlaySound() {
        JButton play = new JButton("Play");//here we make the button
        play.addActionListener(new ActionListener() {//here we tell what the button will do
        public void actionPerformed(ActionEvent e) {
            playTheSound();//when its clicked call this method
        }
    });

    this.add(play);
    this.pack();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setVisible(true);
}

private void SoundEffect(URL url) {
    try {
        // Set up an audio input stream piped from the sound file.
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
        // Get a clip resource.
        clip = AudioSystem.getClip();
        // Open audio clip and load samples from the audio input stream.
        clip.open(audioInputStream);
    } catch (UnsupportedAudioFileException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (LineUnavailableException e) {
        e.printStackTrace();
    }
}

// Play or Re-play the sound effect from the beginning, by rewinding.
public void playTheSound() {

    URL url = getClass().getResource("click.wav");//You can change this to whatever other sound you have
    SoundEffect(url);//this method will load the sound

    if (clip.isRunning())
        clip.stop();   // Stop the player if it is still running
    clip.setFramePosition(0); // rewind to the beginning
    clip.start();     // Start playing

    }

}

you can always change "click.wav" for another sound, including .au files.

0
Andrew Thompson On

As mikera & Basilio German note, both AU & WAV would be good choices for short sound effects as used in games. The current JRE supports the types returned by AudioSystem.getAudioFileTypes(), but I would stick with one of those two.

The Clip class provides easy methods to load and play sound bytes.

As to an example, here is the example from the Java Sound info. page.

import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;

public class LoopSound {

    public static void main(String[] args) throws Exception {
        URL url = new URL(
            "http://pscode.org/media/leftright.wav");
        Clip clip = AudioSystem.getClip();
        // getAudioInputStream() also accepts a File or InputStream
        AudioInputStream ais = AudioSystem.
            getAudioInputStream( url );
        clip.open(ais);
        // loop continuously
        clip.loop(-1);
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // A GUI element to prevent the Clip's daemon Thread
                // from terminating at the end of the main()
                JOptionPane.showMessageDialog(null, "Close to exit!");
            }
        });
    }
}
0
RoneRackal On

File formats for audio are all depending on what you need. A MIDI file uses notes and such, and is therefore suited for simple background music, but a MIDI file would not be able to make specific sounds like explosions, gunfire, whatever it may be. Think of MIDIs as music for musical instruments, it isn't used for sound effects. This is where WAV or MP3 files come into play, since they play sound as a wave they can play any sound really. They are larger files (WAV uncompressed so even larger) but they are used for sound effects often. There are other formats to use also, just search around. You shouldn't be basing sound format on what is easiest to use, it really depends on what exactly you are using it for (music vs sound effects etc).

0
mikera On

Java supports a pretty wide range of sound formats.

If you are just using the basic Java Sound API (which is fine for basic effects), then the following may be helpful from the Oracle FAQ:

What audio formats does Java Sound support?
Java Sound supports the following audio file formats: AIFF, AU and WAV. It also supports the following MIDI based song file formats: SMF type 0 (Standard MIDI File, aka .mid files), SMF type 1 and RMF.

I've successfully used both AU and WAV.

0
helloWorldB On

You can use the Clip class and use .Wav or .Au for small short sound effects. if you are trying to play mp3 music however you can always use an mp3 java library like javazoom.