Results 1 to 4 of 4

Thread: Playing WAV files

Threaded View

  1. #1

    Thread Starter
    Member
    Join Date
    Mar 2008
    Posts
    54

    Playing WAV files

    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();
    }
    }
    Last edited by 01010011; Nov 19th, 2008 at 11:19 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width