I have succeeded to play mp3 files, but I want to play them in following way:
Assume I have two buttons: Button1
and Button2
. If I click But
onton1
then audio file A.mp3
plays. After this click on Button2
then audio file A.mp3
stops and B.mp3
plays. Then again click on Button1
to stop B.mp3
and play A.mp3
instantly and so on.
But when I again try to click on Button1
or Button2
, both the buttons become inactive.
I want to play by Button1
and Button2
many times, while switching on both buttons again and again, but I am able to play only one time switching.
The following is my code. (I used Worker
class and javazoom (jl1.0.1.jar
)
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javax.swing.*;
import javazoom.jl.player.Player;
public class WorkerDemo extends JFrame
{
Player p;
private boolean isStarted = false;
private JLabel counterLabel = new JLabel("Not started");
private Worker worker = new Worker();
private JButton startButton = new JButton(new AbstractAction("Start")
{
@Override
public void actionPerformed(ActionEvent arg0)
{
if(isStarted)
{
p.close();
worker.cancel(true);
}
FileInputStream fis = null;
try
{
fis = new FileInputStream("--------- A.mp3 (File path) ---------------");
BufferedInputStream bis = new BufferedInputStream(fis);
p = new Player(bis);
worker.execute();
System.out.println("m in condition");
}
catch(Exception eeee)
{
System.out.println(eeee);
}
}
});
private JButton stop = new JButton(new AbstractAction("Stop")
{
@Override
public void actionPerformed(ActionEvent arg0) {
if(isStarted)
{
p.close();
worker.cancel(true);
}
FileInputStream fis = null;
try
{
fis = new FileInputStream("------------ B.mp3 (File path) ----------------");
BufferedInputStream bis = new BufferedInputStream(fis);
p = new Player(bis);
worker.doInBackground();
worker.execute();
System.out.println("i am in canceled");
}
catch(Exception eeee)
{
System.out.println(eeee);
}
}
});
public WorkerDemo()
{
add(startButton, BorderLayout.WEST);
add(counterLabel, BorderLayout.CENTER);
add(stop, BorderLayout.EAST);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class Worker extends SwingWorker<Void, Integer>
{
int counter = 0;
@Override
protected Void doInBackground() throws Exception
{
p.play();
return null;
}
}
public static void main(String[] args)
{
new WorkerDemo();
}
}
i also want to add seekbar for my mp3 files. plz suggest me for seekbar too