SHARE
TWEET

Untitled

a guest Jan 21st, 2019 45 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.AudioSystem;
  4. import javax.sound.sampled.Clip;
  5. import javax.sound.sampled.LineUnavailableException;
  6. import javax.sound.sampled.UnsupportedAudioFileException;
  7.  
  8. public class Sound{
  9.  
  10. private Clip sound;
  11.  
  12. public Sound(String location){
  13.  
  14.     try{
  15.         sound = AudioSystem.getClip();
  16.         File file = new File(location);
  17.         sound.open(AudioSystem.getAudioInputStream(file));
  18.     }
  19.     catch(IOException | LineUnavailableException | UnsupportedAudioFileException error){
  20.         System.out.println(error);
  21.     }
  22.  
  23. }
  24.  
  25. public void play(){
  26.  
  27.     sound.start();
  28.  
  29. }
  30.  
  31. }
  32.    
  33. File soundFile = new File( "something.wav" );
  34. AudioInputStream audioInputStream = AudioSystem.getAudioInputStream( soundFile );
  35. clip = AudioSystem.getClip();
  36. clip.open(audioInputStream);
  37. clip.start();//This plays the audio
  38.    
  39. private final int BUFFER_SIZE = 128000;
  40. private AudioInputStream audioStream;
  41. private SourceDataLine sourceLine;
  42. /**
  43.  * @param filename the name of the file that is going to be played
  44.  */
  45.  public void playSound(String filename){
  46. try {
  47.     audioStream = AudioSystem.getAudioInputStream(new File(filename));
  48. } catch (Exception e){
  49.     e.printStackTrace();
  50. }
  51. try {
  52.     sourceLine = (SourceDataLine) AudioSystem.getLine(new DataLine.Info(SourceDataLine.class, audioStream.getFormat()));
  53.     sourceLine.open(audioStream.getFormat());
  54. } catch (LineUnavailableException e) {
  55.     e.printStackTrace();
  56. } catch (Exception e) {
  57.     e.printStackTrace();
  58. }
  59. sourceLine.start();
  60. int nBytesRead = 0;
  61. byte[] abData = new byte[BUFFER_SIZE];
  62. while (nBytesRead != -1) {
  63.     try {
  64.         nBytesRead = audioStream.read(abData, 0, abData.length);
  65.     } catch (IOException e) {
  66.         e.printStackTrace();
  67.     }
  68.     if (nBytesRead >= 0) {
  69.         @SuppressWarnings("unused")
  70.         int nBytesWritten = sourceLine.write(abData, 0, nBytesRead);
  71.     }
  72. }
  73. sourceLine.drain();
  74. sourceLine.close();
  75. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top