简体   繁体   中英

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. 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'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?

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

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 */
} });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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