Free, tested & ready to use examples!
AnyExample.com
 
Web anyexample.com
 

Java play WAV sound file

abstract 
There is source code of simple class AePlayWave in this article, which can play WAV(AUFF, SND, AU might also be supported) sound files asynchronously (in a separate thread, without interruption of main program). It is possible to use it in console or GUI Java programs for playing user notification sounds. There is also trivial RSS-feed checker, which plays various sounds on rss-feed update.
compatible 
  • Sun Java 1.5 or higher
  • Our class extends Java Thread class to be asynchronous. There are two constructors - AePlayWave(String wavfile) with has only one argument - file name, and AePlayWave(String wavfile, Position p), which takes file name and Position constant, either Position.LEFT or Position.RIGHT -- this is simple balance control, which can toggle only left or right channel of stereo sound (useful for storing two different sounds in single wave file).

    Various javax.sound.sampled classes are used to prepare audio input stream and audio data line. Afterwards, we simply read and write (through 512Kb buffer, which is suitable for most formats) sound data from file to sound device.

    source code: Java
     
    import java.io.File; 
    import java.io.IOException; 
    import javax.sound.sampled.AudioFormat; 
    import javax.sound.sampled.AudioInputStream; 
    import javax.sound.sampled.AudioSystem; 
    import javax.sound.sampled.DataLine; 
    import javax.sound.sampled.FloatControl; 
    import javax.sound.sampled.LineUnavailableException; 
    import javax.sound.sampled.SourceDataLine; 
    import javax.sound.sampled.UnsupportedAudioFileException; 
     
    public class AePlayWave extends Thread { 
     
        private String filename;
     
        private Position curPosition;
     
        private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb 
     
        enum Position { 
            LEFT, RIGHT, NORMAL
        };
     
        public AePlayWave(String wavfile) { 
            filename = wavfile;
            curPosition = Position.NORMAL;
        } 
     
        public AePlayWave(String wavfile, Position p) { 
            filename = wavfile;
            curPosition = p;
        } 
     
        public void run() { 
     
            File soundFile = new File(filename);
            if (!soundFile.exists()) { 
                System.err.println("Wave file not found: " + filename);
                return;
            } 
     
            AudioInputStream audioInputStream = null;
            try { 
                audioInputStream = AudioSystem.getAudioInputStream(soundFile);
            } catch (UnsupportedAudioFileException e1) { 
                e1.printStackTrace();
                return;
            } catch (IOException e1) { 
                e1.printStackTrace();
                return;
            } 
     
            AudioFormat format = audioInputStream.getFormat();
            SourceDataLine auline = null;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
     
            try { 
                auline = (SourceDataLine) AudioSystem.getLine(info);
                auline.open(format);
            } catch (LineUnavailableException e) { 
                e.printStackTrace();
                return;
            } catch (Exception e) { 
                e.printStackTrace();
                return;
            } 
     
            if (auline.isControlSupported(FloatControl.Type.PAN)) { 
                FloatControl pan = (FloatControl) auline
                        .getControl(FloatControl.Type.PAN);
                if (curPosition == Position.RIGHT) 
                    pan.setValue(1.0f);
                else if (curPosition == Position.LEFT) 
                    pan.setValue(-1.0f);
            } 
     
            auline.start();
            int nBytesRead = 0;
            byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];
     
            try { 
                while (nBytesRead != -1) { 
                    nBytesRead = audioInputStream.read(abData, 0, abData.length);
                    if (nBytesRead >= 0) 
                        auline.write(abData, 0, nBytesRead);
                } 
            } catch (IOException e) { 
                e.printStackTrace();
                return;
            } finally { 
                auline.drain();
                auline.close();
            } 
     
        } 
    } 
     

    You could use following thread starting code, to play sounds by this class:

    source code: Java
     
    new AePlayWave("test.wav").start();
     

    All exceptions are intercepted, error messages is written to standard error stream (stderr).

    Below is more detail example, which checks RSS feed every 2-3 minutes and

    • plays "nochange.wav" if RSS feed didn't change
    • plays "change.wav" if RSS feed changed (well, length of RSS feed changed)
    • plays "error.wav" if an error occurred while getting RSS feed

    Record or found somewhere wave files rename them to names given above and put to the program directory (which contains ExWave.class)

    By default, program use Yahoo! World News RSS feed. You may specify another RSS feed URL in command line, like this:

     
    java ExWave http://www.anyexample.com/rss/lastest/
    

    source code: Java
     
    // Don't forget to save AePlayWave source to AePlayWave.java 
    // and compile it  
    import java.io.BufferedReader; 
    import java.io.IOException; 
    import java.io.InputStream; 
    import java.io.InputStreamReader; 
    import java.net.MalformedURLException; 
    import java.net.URL; 
     
     
    public class ExWave { 
     
        public static void main(String[] args) throws MalformedURLException 
        { 
            String rss_url = "http://rss.news.yahoo.com/rss/world"; 
            // Yahoo! News RSS -- default  
            if (args.length > 0) 
                rss_url = args[0]; // or command line argument 
     
            int prevLen = -1;
     
            while(true) { 
                String result = "";
     
                URL url = new URL(rss_url);
                InputStream in;
     
                try { 
                    System.out.println("Checking RSS feed " + rss_url);
                    in = url.openStream();
                    BufferedReader ureader = new BufferedReader(new InputStreamReader(in));
     
                    int length = 0;
                    String str;
                    // Downloading and computing length 
                    while ( (str = ureader.readLine()) != null ) { 
                        // This condition removes lines which contains RSS comments 
                        // Yahoo News RSS feed contains some technical information 
                        // in RSS comments 
                        if (str.indexOf("<!--") != -1) 
                            continue;
                        length += str.length();
                    } 
     
                    System.out.println("Length: " + String.valueOf(length) + " characters");
                    if (prevLen != -1) { // first time, prevLen == -1, can't compare with previous value 
                        if (prevLen != length) { 
                            System.out.println("Length changed!");
                            result = "change";
                        } 
                        else { 
                            result = "nochange";
                            System.out.println("No change");
                        } 
                    } 
     
                    prevLen = length;
                    in.close();
                } catch (IOException e1) { 
                    System.out.println("Error");
                    result = "error";
                } 
     
                if (result != "") 
                    new AePlayWave(result+".wav").start(); // playing WAVE file 
     
                int sleep_sec = 120 +  (int)(Math.random() * 60);
                System.out.println("Sleeping for "+ String.valueOf(sleep_sec) + " seconds");
     
                try {Thread.sleep(sleep_sec*1000);}  // Sleeping 
                catch (InterruptedException e) {e.printStackTrace();} 
            } 
        } 
    } 
     
    warning 
  • All AePlayWave class error messages are written to standard error stream (stderr)
  • This example does not support complex sound formats like mp3 or ogg
  • tested 
  • JDK 1.5
  •  


     
    © AnyExample 2010-2013
    License | Privacy | Contact