简体   繁体   English

在 JFugue 中暂停音乐

[英]Pausing Music in JFugue

I am working on a program that plays music in the background via multithreading, because the GUI freezes up otherwise.我正在开发一个通过多线程在后台播放音乐的程序,否则 GUI 会冻结。 I have a basic knowledge of multithreading (volatile, synchronizing, etc.) but I was wondering how to immediately stop/pause a thread (even when processes are processing).我对多线程(易失性、同步等)有基本的了解,但我想知道如何立即停止/暂停线程(即使正在处理进程)。 I have the music looping in the background but if I hook a stop variable up to the loop the song has to stop playing for the music to stop.我的音乐在后台循环播放,但是如果我将停止变量连接到循环,则歌曲必须停止播放才能停止播放。 So my question remains, from the parent thread is there any way to immediately pause or terminate the music in the middle of the song, because I have audio to play after it.所以我的问题仍然存在,从父线程是否有任何方法可以立即暂停或终止歌曲中间的音乐,因为我有音频可以播放。

First, most loops in a thread should look similar to this:首先,线程中的大多数循环应该类似于:

while(!isInterrupted()) {
    try {
       // do something (like play song)
    } catch (InterruptedException e) {
        interrupt();
    }
}

If there are blocking calls inside the loop (which it sounds like from your description), they likely allow interrupt().如果循环内有阻塞调用(从您的描述中听起来像),它们可能允许中断()。 A call to interrupt() from the outside of the thread will break the blocking call and dump you into the catch block.从线程外部调用interrupt() 将中断阻塞调用并将您转储到catch 块中。 This ends up clearing the "interrupt" flag, so you need to call interrupt again to get out of the loop.这最终会清除“中断”标志,因此您需要再次调用中断以退出循环。

Depending on how you're playing music:根据您播放音乐的方式:

  • If you're using a library that has a "pause" or "stop" method to play the music, you can just use that.如果您使用的库具有“暂停”或“停止”方法来播放音乐,则可以使用它。 Looks like you're using jFugue - its player has a pause() method - have you tried calling that?看起来你正在使用 jFugue - 它的播放器有一个 pause() 方法 - 你试过调用它吗?
  • If you're doing something else, you'll need to keep track of the song's position and call interrupt() on the thread.如果您正在做其他事情,则需要跟踪歌曲的位置并在线程上调用 interrupt()。 If you want to restart, you'll need to seek back to the tracked position如果要重新启动,则需要返回到跟踪位置

Note that if you want to restart with the above loop, you'll need a nested loop such as:请注意,如果要使用上述循环重新启动,则需要一个嵌套循环,例如:

while(true) {
    while(!isInterrupted()) {
        ...
    }
}

If you only have the !isInterrupted() loop, the thread will finish, and cannot be restarted.如果您只有 !isInterrupted() 循环,线程将完成,并且无法重新启动。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM