简单讲述java如何实现播放器功能。

java音频播放器备份,支持wav,mp3

都是摘抄于网络,wav播放mp3播放

播放wav版本

  • 不需要其他jar包
  • 代码:
  1. package com;
  2. import javax.sound.sampled.*;
  3. import java.io.File;
  4. /*
  5. wav播放器,不支持mp3
  6. */
  7. public class AePlayWave extends Thread {
  8. private String name;
  9. public AePlayWave(String name) {
  10. this.name = name;
  11. }
  12. @Override
  13. public void run() {
  14. File file = new File(name);
  15. AudioInputStream audioInputStream = null;
  16. try {
  17. audioInputStream = AudioSystem.getAudioInputStream(file);
  18. } catch (Exception e) {
  19. e.printStackTrace();
  20. return;
  21. }
  22. AudioFormat format = audioInputStream.getFormat();
  23. SourceDataLine auline = null;
  24. DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
  25. try {
  26. auline = (SourceDataLine) AudioSystem.getLine(info);
  27. auline.open(format);
  28. } catch (Exception e) {
  29. e.printStackTrace();
  30. return;
  31. }
  32. auline.start();
  33. int nBytesRead = 0;
  34. byte[] abbytes = new byte[512];
  35. try {
  36. while ((nBytesRead = audioInputStream.read(abbytes, 0, abbytes.length)) != -1) {
  37. if (nBytesRead >= 0) {
  38. auline.write(abbytes, 0, nBytesRead);
  39. }
  40. }
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. return;
  44. } finally {
  45. auline.drain();
  46. auline.close();
  47. }
  48. }
  49. }

MP3播放

  1. package com;
  2. import javazoom.jl.decoder.JavaLayerException;
  3. import javazoom.jl.player.Player;
  4. import java.io.BufferedInputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileNotFoundException;
  8. /*
  9. mp3播放器
  10. */
  11. public class AudioPlayer extends Thread {
  12. Player player;
  13. File music;
  14. //构造方法
  15. public AudioPlayer(String fileName) {
  16. this.music = new File(fileName);
  17. }
  18. //重写run方法
  19. @Override
  20. public void run() {
  21. super.run();
  22. try {
  23. play();
  24. } catch (FileNotFoundException | JavaLayerException e) {
  25. // TODO Auto-generated catch block
  26. e.printStackTrace();
  27. }
  28. }
  29. //播放方法
  30. public void play() throws FileNotFoundException, JavaLayerException {
  31. BufferedInputStream buffer =
  32. new BufferedInputStream(new FileInputStream(music));
  33. player = new Player(buffer);
  34. player.play();
  35. }
  36. }