How to play different sounds in Java?

I am trying to play sounds in java ...

private Clip clip; public Sound(String filename) { try{ AudioInputStream ais; ais = AudioSystem.getAudioInputStream(this.getClass().getResource(filename)); clip = AudioSystem.getClip(); clip.open(ais); }catch(Exception e){e.printStackTrace();} } public void playSFX() { clip.stop(); clip.setFramePosition(0); clip.start(); } 

I am using the above code with .wav files. I can successfully use certain .wav clips; however, I cannot play other .wav clips. What am I doing wrong? Also worth noting: I want to play short (and 3 seconds) sound effects. I get an UnsupportedAudioFileException for certain clips that don’t play (they are also .wav). Raw clip sample: Work clip example: link

+4
source share
2 answers

As previous people say, some WAV formats are not supported. I will just add a little more detail.

I often run WAVs that are encoded in 24-bit or 32-bit, when 16-bit is the maximum supported by javax.sound.sampled support.

To find out about a specific WAV file, if you have Windows, you can right-click the file and check the properties and the summary tab. I do not know what the equivalent is in a MAC or Linux system.

Once you recognize the format, you can check to see if it is supported by code in this tutorial: http://download.oracle.com/javase/tutorial/sound/converters.html See the discussion in the Recording Sound Files section for a discussion of where they are. introduce the AudioSystem method, "isFileTypeSupported".

Here is a list of formats supported on my PC. I got this list by checking the LineInfo object through the Eclipse debugger. I suspect they are standard, but I'm not sure:

 BigEndian = false, PCM_UNSIGNED, channels = 1, bits = 8 BigEndian = false, PCM_SIGNED, channels = 1, bits = 8 BigEndian = false, PCM_SIGNED, channels = 1, bits = 16 BigEndian = true, PCM_SIGNED, channels = 1, bits = 16 BigEndian = false, PCM_UNSIGNED, channels = 2, bits = 8 BigEndian = false, PCM_SIGNED, channels = 2, bits = 8 BigEndian = false, PCM_SIGNED, channels = 2, bits = 16 BigEndian = true, PCM_SIGNED, channels = 2, bits = 16 

Most of the WAV files I work with are second and last in the list above: small end, 16-bit, PCM_SIGNED, stereo encoded at 44100 frames per second.

The following code can help you determine the format of your .wav files.

 InputStream inStream = YourClass.class.getResourceAsStream("YourSound.wav"); AudioInputStream aiStream = AudioSystem.getAudioInputStream(inStream); AudioFormat audioFmt = aiStream.getFormat(); DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFmt); System.out.println(info); 
+1
source

As far as I know, some formats are simply not supported. Please check which formats of these WAVs work and which do not.

By format, I mean something like: http://en.wikipedia.org/wiki/WAV#WAV_file_compression_codecs_compared

Then you can simply convert to a format that works.

0
source

All Articles