0

I'm making a simple MP3Player in Java. I have managed to play a .mp3 file but when I start playing the whole program freezes and I can't click any buttons in the program. I need help making the pause button, or any other button work after I start playing. This is my code:

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.InputStream;
    import java.net.URL;
    import javazoom.jl.player.advanced.AdvancedPlayer;
    import javax.swing.*;

    public class MP3Player extends JFrame{

    public MP3Player(){
        JPanel jpBottom = new JPanel();
        JButton btnPlay = new JButton("Play");
        JButton btnPause = new JButton("Pause");

        jpBottom.add(btnPause);
        jpBottom.add(btnPlay);

        Container cp = this.getContentPane();
        BorderLayout bl = new BorderLayout();
        cp.setLayout(bl);
        cp.add(jpBottom, BorderLayout.SOUTH);

        btnPlay.addActionListener(
                new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        Play("file:///C://a.mp3");
                    }
                }
        );

        this.setVisible(true);
        this.setSize(250, 100);
        this.setTitle("MP3 Player");
        this.setLocation(100, 100);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void Play(String path){
        try{
            URL url = new URL(path);
            InputStream in = url.openStream();
            //Player pl = new Player(in);
            //pl.play();
            AdvancedPlayer pl = new AdvancedPlayer(in);

            pl.getPlayBackListener();
            pl.play();             
        }
        catch(Exception e){
            System.out.println("Feil: "+e);
        }
    }

    public static void main(String[] args) {
        MP3Player n = new MP3Player();
    }
}

2 Answers 2

1

You should call Play() method in a separate thread and also have a good understanging of Multithreding in Swing. At least you should read about SwingUtilities.invokeLater()

1

I need help making the pause button, ..

The method to pause the player is stop(). But that code creates the AdvancedPlayer local to a method. Instead, the class needs to declare an AdvancedPlayer attribute and reference that class attribute in the actionPerformed() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.