AudioPlayer.java 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package audio;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import javazoom.jl.decoder.JavaLayerException;
  6. import javazoom.jl.player.Player;
  7. public class AudioPlayer{
  8. private Player clip;
  9. private FileInputStream fis;
  10. private Song s;
  11. private Thread thread;
  12. public AudioPlayer() {
  13. clip = null;
  14. }
  15. public void setClip(Song s) {
  16. try {
  17. if(clip!=null)
  18. clip.close();
  19. this.s = s;
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. public void play() {
  25. try {
  26. fis = new FileInputStream(s.getAudio());
  27. clip = new Player(fis);
  28. } catch (JavaLayerException | FileNotFoundException e1) {
  29. e1.printStackTrace();
  30. }
  31. Thread thread = new Thread(new Runnable() {
  32. @Override
  33. public void run() {
  34. if(clip != null){
  35. try {
  36. clip.play();
  37. } catch (JavaLayerException e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }});
  42. thread.start();
  43. }
  44. public void close() {
  45. if(clip != null)
  46. {
  47. clip.close();
  48. clip = null;
  49. try {
  50. if(fis != null)
  51. fis.close();
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55. if(thread != null && thread.isAlive())
  56. thread.stop();
  57. }
  58. }
  59. public long getProgress()
  60. {
  61. if(clip != null)
  62. return clip.getPosition()*1000;
  63. else
  64. return 0L;
  65. }
  66. }