使用JLayer停止/静音播放音乐

时间:2011-03-13 14:04:22

标签: mute jlayer

我正在使用jlayer在我的程序中播放mp3文件但是在jlayer文档中我找不到任何关于停止播放音乐并从停止的地方继续播放的有用信息。任何想法?

我的计划如下:


package sounds;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;

/**
 * Wayne, K. (2005). How to Play an MP3 File in Java. 
 * Available: http://introcs.cs.princeton.edu/faq/mp3/mp3.html.
 * Last accessed 10th Mar 2011.
 * @author temelm
 */
public class MP3 {
  private String filename;
  private Player player;

  /**
   * MP3 constructor
   * @param filename name of input file
   */
  public MP3(String filename) {
    this.filename = filename;
  }

  /**
   * Creates a new Player
   */
  public void play() {
    try {
      FileInputStream fis = new FileInputStream(this.filename);
      BufferedInputStream bis = new BufferedInputStream(fis);

      this.player = new Player(bis);
    } catch (Exception e) {
        System.err.printf("%s\n", e.getMessage());
    }

    new Thread() {
      @Override
      public void run() {
        try {
          player.play();
        } catch (Exception e) {
            System.err.printf("%s\n", e.getMessage());
        }
      }
    }.start();
  }

  /**
   * Closes the Player
   */
  public void close() {
    if (this.player != null) {
      this.player.close();
    }
  }

  /////////////////////////

  /**
   * Plays '01 Maenam.mp3' in an infinite loop
   */
  public static void playMaenam() {
    MP3 mp3 = new MP3("./01 Maenam.mp3");

    mp3.play();

    while (true) {
      if (mp3.player.isComplete()) {
        mp3.close();
        mp3.play();
      }
    }
  }
}

3 个答案:

答案 0 :(得分:2)

您可以暂停其线程以获得简单的暂停功能。

答案 1 :(得分:2)

在线程中一次只播放一帧,如果设置了“pause”标志,则暂停线程......

如果按下输入键(在控制台中)并且“退出”以终止应用程序,则下面的代码暂停/恢复播放器线程。

            final AtomicBoolean pause = new AtomicBoolean(false);

        final Player player = new Player(bis);
        Thread playerThread = new Thread() {
            @Override
            public void run() {
                try {
                    while (player.play(1)) {
                        if(pause.get()) {
                            LockSupport.park();
                        }
                    }
                }
                catch (Exception e) {
                    System.err.printf("%s\n", e.getMessage());
                }
            }
        };

        playerThread.start();

        Scanner scanner = new Scanner(System.in);
        String s = null;
        while (!(s = scanner.nextLine()).equals("exit")) {
            if (s.isEmpty()) {
                pause.set(!pause.get());
                if (!pause.get()) {
                    LockSupport.unpark(playerThread);
                }
            }
        }
        System.exit(0);

答案 2 :(得分:0)

我从fileInputStream中获取了我的mp3。当我想暂停时,我会(fis是fileinputstream)fis.available()(或类似的东西)。这将给出流中剩余的字节数...如果在启动之前执行此操作,则会获得总长度。所以剩下的总剩余金额=当前位置。然后我只是创建一个新的输入流并执行fis.skip(theamount);恢复..有意思的方法,但是它有效..