How to play different sounds in Java?
I want to play sound 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 here. The above code is used in the wav file I can play some successfully Wav fragment; But I can't play anything else Wav fragment What on earth did I do wrong? Also note: I want to play a short (< 3 seconds) sound effect I got unsupported audiofileexception for some clips that don't play (they are also. WAV) Example non working clip: linksample working clip: link
Solution
As mentioned before, some wav formats are not supported I just want to add a little detail
I often encounter wav encoded in 24 bit or 32 bit, when 16 bit is javax sound. The maximum value supported by sampled
To understand a specific Wav file, if you have windows, you can right-click the file and check the properties and summary tab I don't know what the equivalent is on MAC or Linux systems
Once you understand the format, you can check that the code in this tutorial supports: http://download.oracle.com/javase/tutorial/sound/converters.html Refer to the discussion in "writing sound files", which describes the audiosystem method "isfiletypesupported"
The following is a list of supported formats on my PC I got this list by checking the lineinfo object through the eclipse debugger I doubt these are standard, but I'm not sure:
BigEndian = false,PCM_UNSIGNED,channels = 1,bits = 8 BigEndian = false,PCM_SIGNED,bits = 16 BigEndian = true,bits = 16 BigEndian = false,channels = 2,bits = 16
Most of the WAV files I use are the penultimate in the list above: small end, 16 bit, stereo, encoded at 44100 FPS
The following code can also help you determine Wav file format
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);