Found this sniplet of code on various websites to use this way of playing a wav file however im getting this error message.

javax.sound.sampled.UnsupportedAudioFileException: could not get audio input stream from input file

Update 1 - I know the wav file has to be 8khz, is there a way to convert any wav file to 8khz?

static class addAudioAction implements ActionListener {
	
	public void actionPerformed(ActionEvent e) {
		
		playWave();
		
	}
}

static void playWave() { 
	 
	try {
		AudioInputStream audioInputStream;
		File file = new File("test.wav");
		audioInputStream = AudioSystem.getAudioInputStream(file);
		Clip line;
		line = (Clip) AudioSystem.getLine(new DataLine.Info(Clip.class, audioInputStream.getFormat()));
		line.open(audioInputStream);
		line.start();
		line.drain();
		audioInputStream.close();
	}
	catch (Exception e) 
	{
		e.printStackTrace();
	}
		
	Toolkit.getDefaultToolkit().beep();
}

Edited 5 Years Ago by StevoLord: n/a

Hrm...

Here is what I use to play sounds:

private void playSound(String file) {
		try {
			Clip sound = AudioSystem.getClip();
			sound.open(AudioSystem.getAudioInputStream(
					getClass().getResource(file)));
			sound.start();
		} 
		catch (UnsupportedAudioFileException e1) { }
		catch (IOException e2) { } 
		catch (LineUnavailableException e3) { }
	}

So that you can do:

playSound("sounds/click.WAV");

Of course, you may want to preload your audio files and do something clever with the caught exceptions.

Edited 5 Years Ago by ztini: n/a

Thanks for the reply Ztini, does that code you posted allow for any audio file type to be played or just wav files? I've got it to work for 8khz wav files but im kinda wanting any wav files and possibly mp3.

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.

The Java Sound engine can render 8 or 16 bit audio data, in mono or stereo, with sample rates from 8KHz to 48KHz, that might be found in streaming audio or any of the supported file formats.

According to: http://java.sun.com/products/java-media/sound/techReference/javasoundfaq.html

This question has already been answered. Start a new discussion instead.