Hello,
I am trying to figure out how to play .WAV files in my Java program. Here is the code. I get no errors when I compile but no sound plays. I placed the wav file in the same directory as my java and class files. I also tried to compile through the command line, passing the name of the file as the argument. I also instantuated my Sound class in the main of my driver program - Sound sound = new Sound("nightingale2.wav"); . Not sure what I did wrong. Any assistence will be greatly appreciated!
Code:import java.io.*; import javax.sound.sampled.*; import javax.swing.JOptionPane; public class Sound { File soundFile; public Sound( String file) { soundFile = new File(file); } public void play() { try { AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile); AudioFormat format = ais.getFormat(); JOptionPane.showMessageDialog(null, "Format: " + format); DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); SourceDataLine source = (SourceDataLine) AudioSystem.getLine(info); source.open(format); source.start(); int read = 0; byte[] audioData = new byte[16384]; while (read > -1) { read = ais.read(audioData, 0, audioData.length); if (read >=0) { source.write(audioData, 0, read); } } source.drain(); source.close(); }catch (Exception exc) { JOptionPane.showMessageDialog(null, "Error: " + exc.getMessage()); exc.printStackTrace(); } System.exit(0); } public static void main( String [] arguments) { if (arguments.length > 1) { JOptionPane.showMessageDialog(null, "Usage: Java Speaker Filename"); System.exit(-1); } Sound sound = new Sound(arguments[0]); sound.play(); } }




Reply With Quote