Guest User

Audio Looping

a guest
Apr 21st, 2013
425
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. public class BackgroundMusic extends Thread
  2. {
  3. private String fileLocation;
  4. private Thread t;
  5. private volatile boolean isPlaying;
  6. AudioInputStream audioInputStream;
  7. SourceDataLine line;
  8.  
  9. public BackgroundMusic(String path){
  10. fileLocation = path;
  11.  
  12. }
  13.  
  14. public void play()
  15. {
  16. isPlaying = true;
  17. t = new Thread(this);
  18. t.start();
  19. }
  20.  
  21. public void stopPlaying(){
  22. isPlaying = false;
  23. }
  24.  
  25. public void run ()
  26. {
  27. while(isPlaying)
  28. playSound(fileLocation);
  29. }
  30. private void playSound(String fileName)
  31. {
  32. File soundFile = new File(fileName);
  33. audioInputStream = null;
  34. try
  35. {
  36. audioInputStream = AudioSystem.getAudioInputStream(soundFile);
  37. }
  38. catch (Exception e)
  39. {
  40. e.printStackTrace();
  41. }
  42. AudioFormat audioFormat = audioInputStream.getFormat();
  43.  
  44. DataLine.Info info = new DataLine.Info(SourceDataLine.class,audioFormat);
  45. try
  46. {
  47. line = (SourceDataLine) AudioSystem.getLine(info);
  48. line.open(audioFormat);
  49. }
  50. catch (LineUnavailableException e)
  51. {
  52. e.printStackTrace();
  53. }
  54. catch (Exception e)
  55. {
  56. e.printStackTrace();
  57. }
  58. line.start();
  59. int nBytesRead = 0;
  60. byte[] abData = new byte[128000];
  61. while (nBytesRead != -1 && isPlaying)
  62. {
  63. try
  64. {
  65. nBytesRead = audioInputStream.read(abData, 0, abData.length);
  66. }
  67. catch (IOException e)
  68. {
  69. e.printStackTrace();
  70. }
  71. if (nBytesRead >= 0)
  72. {
  73. int nBytesWritten = line.write(abData, 0, nBytesRead);
  74. }
  75. }
  76. line.drain();
  77. line.close();
  78. }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment