简体   繁体   English

在JLayer中使用一个线程时,如何停止当前播放歌曲?

[英]How to Stop Current Playing Song When using one thread with JLayer?

I recently used a solution to the one-thread-at-a-time problem whe using Jlayer to play mp3 songs in Java. 最近,我使用Jlayer来播放Java中的mp3歌曲,从而解决了一个线程一次的问题。 But this solution by Kaleb Brasee didn't hint at how you could stop the player, ie how could one then call player.close()? 但是Kaleb Brasee提出的解决方案并没有暗示您如何停止播放器,即如何才能调用player.close()?

Kaleb's code was: Kaleb的代码是:

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

and this is the code I put in run() 这是我放入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 :-( 问题在于,这解决了在音乐播放时保持gui处于活动状态的问题(仅在另一个线程中-我想要的),我无法开始播放另一首歌曲了:-(

What could I do? 我能做什么?

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 https://stackoverflow.com/a/16738486/2094045

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 = Executors.newSingleThreadExecutor();
executor.execute(new Runnable() { public void run() { executor.execute(new Runnable(){public void run(){
/* do something */ /* 做一点事 */
} }); }});

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

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