I'm sorry for my bad English :) I have problem with mp 3 player. I'm using jLayer. This is my code
private void formWindowOpened(java.awt.event.WindowEvent evt) { new Thread (){ public void run(){ try { Player prehravac; FileInputStream buff = new FileInputStream(Okno.filename); prehravac = new Player(buff); prehravac.play(); if (prehravac != null) { prehravac.play(); } } catch(Exception e) { } } }.start(); }
In my application i need to play song from the beginning to the end. So when song ends I need to start it again and when window closes I want to stop this song...
Can someone help me with it please ? :) I'm trying to do it for 2 days... I don't know how to stop something in different Thread... Thank you for your help :)
JLayer does not support continuous play, so you have to use a loop to repeatedly start a new player after the old one finished. For example:
try { do { FileInputStream buff = new FileInputStream(Okno.filename); prehravac = new AdvancedPlayer(buff ); prehravac .play(); }while(loop); } catch(Exception ioe) { //TODO error handling }
with loop being a boolean you can set true or false in a different method depending on if you want it to be played just once or repeatedly.
If you want to access the thread later you should at least declare it to a variable. Even better is writing a seperate class that extends thread. Doing so you can add method to the thread you can later call.
For your code it might look something like that:
import java.io.*; import javazoom.jl.player.*; public class MyAudioPlayer extends Thread { private String fileLocation; private boolean loop; private Player prehravac; public MyAudioPlayer(String fileLocation, boolean loop) { this.fileLocation = fileLocation; this.loop = loop; } public void run() { try { do { FileInputStream buff = new FileInputStream(fileLocation); prehravac = new Player(buff); prehravac.play(); } while (loop); } catch (Exception ioe) { // TODO error handling } } public void close(){ loop = false; prehravac.close(); this.interrupt(); } }
With this you can simply create the Thread when and wherever you want like this:
private MyAudioPlayer thePlayer; [... some class code here...] public void yourMethod(){ thePlayer = new MyAudioPlayer("path of the music file", true); thePlayer.start(); }
and if you want to get rid of it at some point call thePlayer.close();
Note that thePlayer should be an instance variable so you can reuse it again. If you only declare it within a method it will disappear after the method is finished.
Hope this helps.