java音乐播放器

音乐播放器

package 音乐播放器;

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Color;
import java.awt.Font;
import java.awt.List;
import java.awt.MenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;



public class MusicPlayer extends JFrame {
    JLabel songNameLabel = null;// 用标签显示状态
    // 四个播放功能键按钮
    JButton btnLast = null; // 上一曲
    JButton btnPlay = null; // 播放/停止
    JButton btnNext = null; // 下一曲
    JButton btnLoop = null; // 循环
    JButton btnAdd = null;// 添加

    JLabel listLabel = null;// 播放列表标签

    List songsList;// 列表

    Vector<AudioClip> songs;// 列表中的歌曲

    AudioClip currentSongs;// 当前歌曲
    // 此处用并发容器,不然会报错误
    HashSet<File> strSongsName = new HashSet<File>();

    Record record = new Record();

    String strCurrentSongName; // 当前选定播放歌曲的名称
    int index = 0; // 记录当前选定播放的歌曲的序号(当前播放的那首歌曲),默认第一首
    boolean isPlayOrStop = true;// 记录播放状态(播放/停止),默认为播放
    boolean isLoop = false; // 记录循环状态,默认为不循环播放

    Thread playerThread; // 音频播放线程
    public MusicPlayer() {
        super("音乐播放器");
        this.setLayout(null);
        this.setBounds(300, 50, 330, 500);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);


        //添加文件
        JMenuBar menuBar=new JMenuBar();
        this.setJMenuBar(menuBar);
        JMenu menu=new JMenu("文件");
        menuBar.add(menu);
        JMenuItem menuAdd=new JMenuItem("添加文件");
        menu.add(menuAdd);
        menuAdd.addActionListener(new ActionListener() {


            public void actionPerformed(ActionEvent e) {
                JFileChooser jc=new JFileChooser();
                jc.showOpenDialog(MusicPlayer.this);

            }
        });
        // 标签:我的音乐播放器/歌曲名
        songNameLabel = new JLabel();
        Font songNameFont = new Font("斜体", Font.ITALIC, 18);
        songNameLabel.setFont(songNameFont);
        songNameLabel.setText("我的音乐播放器");
        songNameLabel.setBounds(10, 10, 300, 40);
        this.getContentPane().add(songNameLabel);

        // 四个播放功能键按钮
        // 构造四个按钮
        btnLast = new JButton();
        btnPlay = new JButton();
        btnNext = new JButton();
        btnLoop = new JButton();
        // 添加歌曲
        btnAdd = new JButton();

        // 设置位置和大小
        btnLast.setBounds(10, 70, 50, 40);
        btnPlay.setBounds(70, 70, 50, 40);
        btnNext.setBounds(130, 70, 50, 40);
        btnLoop.setBounds(190, 70, 50, 40);
        btnAdd.setBounds(250, 70, 50, 40);

        // 设置图片
        btnLast.setIcon(new ImageIcon("./Image//1.png"));
        btnPlay.setIcon(new ImageIcon("./Image//2.png"));
        btnNext.setIcon(new ImageIcon("./Image//3.png"));
        btnLoop.setIcon(new ImageIcon("./Image//4.png"));
        btnAdd.setIcon(new ImageIcon("./Image//添加.png"));

        // 给按钮添加监听
        MouseListener mlc = new MouseListenerC();// 鼠标监听器对象
        btnLast.addMouseListener(mlc);
        btnPlay.addMouseListener(mlc);
        btnNext.addMouseListener(mlc);
        btnLoop.addMouseListener(mlc);
        btnAdd.addMouseListener(mlc);
        // 添加到框架
        getContentPane().add(btnLast);
        getContentPane().add(btnPlay);
        getContentPane().add(btnNext);
        getContentPane().add(btnLoop);
        getContentPane().add(btnAdd);

        // 以下这段设置歌曲播放列表
        // 设置播放列表的标签
        listLabel = new JLabel("播放列表");
        listLabel.setBounds(10, 120, 100, 30);
        Font listLabelFont = new Font("宋体", Font.BOLD, 15);
        listLabel.setFont(listLabelFont);
        this.getContentPane().add(listLabel);

        // 设置播放列表控件
        songsList = new List();
        songsList.setFont(new Font("斜体", Font.ITALIC, 20));
        songsList.setBounds(10, 150, 250, 300);
        songsList.setBackground(Color.cyan);
        songs = new Vector<AudioClip>();

        // 添加歌曲线程运行
        // add();

        // 读取歌曲列表
        try {
            record.read();
            Iterator<File> it=strSongsName.iterator();
            while(it.hasNext()){
                File file=it.next();
                add(file.getAbsolutePath());
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        songsList.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                currentSongs.stop();
                index = songsList.getSelectedIndex();
                playerThread = new Thread(new MusicRun());
                playerThread.start();
            }
        });
        playerThread = new Thread(new MusicRun());
        playerThread.start();
        this.getContentPane().add(songsList);
        this.setVisible(true);

    }
    class MusicRun implements Runnable{

        public void run() {
            currentSongs = songs.get(index);
            if (isLoop) {
                currentSongs.loop();
            }
            strCurrentSongName =songsList.getItem(index);
            songNameLabel.setText("正在播放:" + strCurrentSongName);
            songsList.select(index);// 在播放列表中选定当前播放歌曲条目
            btnPlay.setIcon(new ImageIcon("./Image//5.png"));// 切换成“停止”图标
            if (isPlayOrStop) {
                currentSongs.play();
            }
        }

    }

    private void add(String str) {
        // 把歌曲文件名加载进来
        songsList.add(new File(str).getName());
        songs.add(loadSound(str));

    }

    // 记录
    class Record {
        private FileWriter fw;
        private FileReader fr;
        private File file;
        private BufferedReader bufr;
        private BufferedWriter bufw;

        public Record() {
            try {
                file = new File("H://Music.txt");
                if (!file.exists()) {
                    file.createNewFile();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 存储
        public void Save(String str) {
            try {

                fw = new FileWriter(file, true);
                bufw = new BufferedWriter(fw);
                bufw.write(str + "\r\n");
            } catch (IOException e) {

            } finally {
                if (bufw != null) {
                    try {
                        bufw.close();
                    } catch (IOException e) {

                    }
                }
                if (fw != null) {
                    try {
                        fw.close();
                    } catch (IOException e) {

                    }
                }

            }
        }

        // 读取文件信息
        public void read() throws FileNotFoundException {
            try {
                fr = new FileReader(file);
                bufr = new BufferedReader(fr);
                String str;
                while ((str = bufr.readLine()) != null) {
                    strSongsName.add(new File(str));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    class MouseListenerC extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent e) {
            JButton btn = (JButton) e.getSource();
            if (btn == btnAdd) {
                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        "*.wav", "wav");
                chooser.setFileFilter(filter);
                int returnVal = chooser.showOpenDialog(MusicPlayer.this);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    boolean flag = strSongsName.add(chooser.getSelectedFile());
                    // 添加歌曲线程运行
                    if (flag) {
                        record.Save(chooser.getSelectedFile().getAbsolutePath());
                        add(chooser.getSelectedFile().getAbsolutePath());
                    }else{
                        JOptionPane.showMessageDialog(null,"已存在相同歌曲 添加失败");
                    }
                }

            }
            currentSongs.stop();
            if (btn == btnPlay) {
                isPlayOrStop = !isPlayOrStop;
            } else if (btn == btnLast) {
                index--;
                if (index < 0) {
                    index = strSongsName.size()- 1;
                }
                isPlayOrStop = true;
                isLoop = false;
            } else if (btn == btnNext) {
                index++;
                index = index % strSongsName.size();
                isPlayOrStop = true;
                isLoop = false;
            } else if (btn == btnLoop) {
                isLoop = !isLoop;
            }

            if (isPlayOrStop) {
                playerThread = new Thread(new MusicRun());
                playerThread.run();
            } else {
                songNameLabel.setText("停止播放:" + strCurrentSongName);
                btnPlay.setIcon(new ImageIcon("./Image//2.png"));
            }

        }

    }

    public static void main(String[] args) {
        MusicPlayer mp = new MusicPlayer();
    }

    public AudioClip loadSound(String filename) {
        URL url = null;
        try {
            url = new URL("file:" + filename);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return Applet.newAudioClip(url);
    }
}

你可能感兴趣的:(java音乐播放器)