SHARE
TWEET

APCS_CH8_EasySound.java

calcpage Mar 13th, 2013 39 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.io.File;
  2. import java.io.IOException;
  3. import javax.sound.sampled.AudioFormat;
  4. import javax.sound.sampled.AudioInputStream;
  5. import javax.sound.sampled.AudioSystem;
  6. import javax.sound.sampled.DataLine;
  7. import javax.sound.sampled.LineUnavailableException;
  8. import javax.sound.sampled.SourceDataLine;
  9.  
  10. /**
  11.  * @author Gary Litvin
  12.  * @version 1.6, 01/01/11
  13.  *
  14.  * Appendix to:
  15.  *
  16.  * <i>Java Methods: Object-Oriented Programming and Data Structures</i>
  17.  * (Skylight Publishing 2011, ISBN 978-0-9824775-7-1)
  18.  *
  19.  * EasySound provides a simple way od playing a sound in an application.
  20.  *
  21.    <xmp>
  22.    Example:
  23.    =======
  24.  
  25.        EasySound bells = new EasySound("bells.wav");
  26.        bells.play();
  27.  
  28.    </xmp>
  29.  */
  30. public class EasySound
  31. {
  32.   private SourceDataLine line = null;
  33.   private byte[] audioBytes;
  34.   private int numBytes;
  35.  
  36.   /**
  37.    * Constructs an <code>EasySound</code> for a given audio file.
  38.    * @param fileName the name or pathname of the audio clip file.
  39.    */
  40.   public EasySound(String fileName)
  41.   {
  42.     File  soundFile = new File(fileName);
  43.     AudioInputStream audioInputStream = null;
  44.     try
  45.     {
  46.       audioInputStream = AudioSystem.getAudioInputStream(soundFile);
  47.     }
  48.     catch (Exception ex)
  49.     {
  50.       System.out.println("*** Cannot find " + fileName + " ***");
  51.       System.exit(1);
  52.     }
  53.  
  54.     AudioFormat audioFormat = audioInputStream.getFormat();
  55.     DataLine.Info info = new DataLine.Info(SourceDataLine.class,
  56.                          audioFormat);
  57.     try
  58.     {
  59.       line = (SourceDataLine)AudioSystem.getLine(info);
  60.       line.open(audioFormat);
  61.     }
  62.     catch (LineUnavailableException ex)
  63.     {
  64.       System.out.println("*** Audio line unavailable ***");
  65.       System.exit(1);
  66.     }
  67.  
  68.     line.start();
  69.  
  70.     audioBytes = new byte[(int)soundFile.length()];
  71.  
  72.     try
  73.     {
  74.       numBytes = audioInputStream.read(audioBytes, 0, audioBytes.length);
  75.     }
  76.     catch (IOException ex)
  77.     {
  78.       System.out.println("*** Cannot read " + fileName + " ***");
  79.       System.exit(1);
  80.     }
  81.   }
  82.  
  83.   /**
  84.    * Plays this <code>EasySound</code>.
  85.    */
  86.   public void play()
  87.   {
  88.     line.write(audioBytes, 0, numBytes);
  89.   }
  90. }
RAW Paste Data
Top