1

我尝试制作一个播放 FLAC 文件的类。为此,我使用jFlac。所以,为了播放一首歌,我需要做:

Player p = new Player();
p.decode("PATH_TO_FLAC");

我把它放在我班级的 run() 方法中。如果我启动线程,那就行了。但我想知道如何暂停。我无法控制 in 中的循环p.decode();,所以我不能使用等待和通知。但Thread.suspend()已弃用。我不知道该怎么办。

我的课:

public class FLACPlayer implements Runnable {
/**
 * Path of the song
 */
private String file;

private org.kc7bfi.jflac.apps.Player player;

/**
 * The thread launching the player
 */
private Thread playerThread;

/**
 * Constructor: initialize the player
 * 
 * @param str
 *            The path of the file to play
 */
public FLACPlayer(String str) {
    file = str;

    player = new org.kc7bfi.jflac.apps.Player();
    this.playerThread = new Thread(this, "AudioPlayerThread");
}

public void play() {
    playerThread.start();
}

@Override
public void run() {
    try {
        player.decode(file);
    } catch (IOException | LineUnavailableException e) {
    }
}

谢谢!

4

4 回答 4

1

通常,应该通过设置一些由线程定期检查的变量(使用适当的同步)来停止线程。然后线程负责自行停止。暂停也是如此——他们可以检查一个变量,然后检查sleep一段时间。

暂停代码不受您控制的线程是危险的,因为您不知道它在做什么。也许它占用了一堆网络端口(只是片刻,它想),现在你已经暂停了它,而这些端口神秘地不可用。也许它正在做一些实时的事情,当你恢复它时,它会处于完全崩溃的状态。

也就是说,您应该阅读并理解为什么Thread.stop和朋友被弃用。基本上,这不是因为它们本身被破坏,而是因为它们经常导致代码被破坏。但是,如果您了解风险和您正在使用的代码,那么调用它们本质上并没有错。

于 2014-01-25T16:21:47.503 回答
0

无论如何,您不能暂停 Java 线程,而且您也不想这样做。

您使用的代码只是一个简单的示例应用程序,它不包含任何暂停播放的方法。您应该检查课程的来源Player;那里包含的代码更复杂,但可以让您更好地控制播放过程,无疑还包括暂停的能力。

于 2014-01-25T16:09:30.393 回答
0

您可以通过中断线程来解决问题。当你中断一个线程时,它会抛出一个被中断的异常,捕获异常并在那里对一个对象进行等待锁定。当您想恢复时,只需在对象上调用 notify 即可。

Object lock=new Object();

@Override
public void run() {
    try {
        player.decode(file);
    } catch (InterruptedException e) {

      synchronized(lock) 
      {
        lock.wait();
      }    

    }
于 2014-01-25T16:16:21.617 回答
0

我认为您已经弄清楚了如何实现这一点 - 但正如 Flavio 建议的那样,您可以执行以下操作

PCMProcessors 中的这个方法应该被覆盖 -

  public void processPCM(ByteData pcm) {
    synchronized (pcmProcessors) {

        int suspensionValue=0;

        Iterator it = pcmProcessors.iterator();
        while (it.hasNext()) {
          //DEFINE THE FLAG FOR SUSPENSION HERE - Logic should be block set ???

           PCMProcessor processor = (PCMProcessor)it.next();
            processor.processPCM(pcm);
        }
    }
  }


    DEFINE A Variable : volatile int flag=Threshold.Value



    Poll this from the main thread which kicks DECODE method 

    Sleep and Resume for whatever time you want
于 2014-01-25T16:48:37.493 回答