JLayer 使用单线程时如何停止当前正在播放的歌曲?
我最近使用了一种解决方案,解决了使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,在调整代码后,我意识到替换当前线程可以解决问题;它允许您开始播放另一首歌曲,即使上一首歌曲尚未完成。
这是新代码:
每次想要播放歌曲时都执行此操作,只需替换现有歌曲的线程,
因此,无论另一首歌曲的进度如何,您都可以播放另一首歌曲
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:
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
这与另一个问题非常相似,您只需一次播放一个音频帧,然后检查标志是否应该暂停,在您的情况下停止播放。
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