JLayer 使用单线程时如何停止当前正在播放的歌曲?

发布于 2024-10-11 05:21:35 字数 588 浏览 2 评论 0原文

我最近使用了一种解决方案,解决了使用 Jlayer 在 Java 中播放 mp3 歌曲时一次一个线程的问题。但是 Kaleb Brasee 的这个解决方案并没有暗示如何停止播放器,即如何调用player.close()?

Kaleb 的代码是:

Executor executor = Executors.newSingleThreadExecutor();  
executor.execute(new Runnable() { public void run() {  
 /* do something */  
} });

这是我放入 run() 中的代码

if(player != null) player.close();  

try{  
player = new Player(new FileInputStream(musicD.getPath()));  
player.play();  
}catch(Exception e){} 

问题在于,这解决了在音乐播放时保持 gui 活动的问题(仅在另一个线程中 - 我想要的),我无法开始播放另一首歌:-(

我能做什么?

I recently used a solution to the one-thread-at-a-time problem whe using Jlayer to play mp3 songs in Java. But this solution by Kaleb Brasee didn't hint at how you could stop the player, i.e how could one then call player.close()?

Kaleb's code was:

Executor executor = Executors.newSingleThreadExecutor();  
executor.execute(new Runnable() { public void run() {  
 /* do something */  
} });

and this is the code I put in run()

if(player != null) player.close();  

try{  
player = new Player(new FileInputStream(musicD.getPath()));  
player.play();  
}catch(Exception e){} 

The problem is that much as this solves the problem of keeping the gui active while the music plays (in only one other thread -- what i'd wanted), I can't start playing another song :-(

What could I do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

﹂绝世的画 2024-10-18 05:21:35

好吧,在调整代码后,我意识到替换当前线程可以解决问题;它允许您开始播放另一首歌曲,即使上一首歌曲尚未完成。

这是新代码:

执行者执行者; //类成员

每次想要播放歌曲时都执行此操作,只需替换现有歌曲的线程,
因此,无论另一首歌曲的进度如何,您都可以播放另一首歌曲

执行器 = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() { 公共 void run() {
/* 做某事 */
} });

Well, after tweaking with the code, I realized that replacing the current thread solves the problem; it allows you to start playing a different song even if the previous one hasn't finished yet.

This is the new code:

Executor executor; //a class member

Doing this every time you want to play a song simply replaces the existing song's thread,
thus allowing you to play another song regardless of the progress of the other

executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() { public void run() {
/* do something */
} });

十六岁半 2024-10-18 05:21:35

这与另一个问题非常相似,您只需一次播放一个音频帧,然后检查标志是否应该暂停,在您的情况下停止播放。

https://stackoverflow.com/a/16738486/2094045

This is very similar to the other question, you can simply play one audio frame at a time, and check a flag if it should pause, in your case stop, playing.

https://stackoverflow.com/a/16738486/2094045

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文