Java MP3Player通过使用Javazoom播放和暂停

问题描述 投票:0回答:2

我正在用Java制作一个简单的MP3Player。我设法播放.mp3文件,但是当我开始播放整个程序冻结时,我无法点击程序中的任何按钮。我开始播放后需要帮助制作暂停按钮或任何其他按钮。这是我的代码:

    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();
    }
}
java mp3 audio-player
2个回答
1
投票

你应该在一个单独的线程中调用Play()方法,并且对Multithreding in Swing有很好的理解。至少你应该读一下SwingUtilities.invokeLater()


1
投票

我需要帮助制作暂停按钮,..

暂停播放器的方法是stop()。但该代码创建了一个方法的AdvancedPlayer本地。相反,该类需要声明一个AdvancedPlayer属性并在actionPerformed()方法中引用该类属性。

© www.soinside.com 2019 - 2024. All rights reserved.