• “拓展知识”已可以正常访问
  • 嘿,姑娘,我又想你了
  • 说下什么是“真正的自己”吧
  • 你知道在自习室小憩醒来,左前方有个美女是什么感觉么?
  • 我也不知说些什么好 可我想和你说说话
  • 不是所有的事情都会顺心如意,也不是所有的事情都要顺你心意
  • 你不穿红裙 也未到杭州 我在西湖这头看荷花 湖对岸都不会有你的身影
  • 这里荒漠寸草不生 后来你来这走了一遭 奇迹般万物生长
  • 我们想去哪里就去哪里,这就是船的真正意义
  • 可能世界上所有努力的目的,都是为了将来可以轻松。

JAVA编写的迷你音乐播放器

有人说 JAVA 可以写音乐播放器么?我想说,JAVA 可以写音乐播放器,相对于其他一些来说,可能会有些不爽,但是他还是可以实现的!

今天,我就上传一下自己在闲暇时间写的一个简易的音乐播放器,好的,有兴趣的呢,可以复制代码来看一下效果,如果其中有一些代码出现了问题呢,可以评论我,我一定会在第一时间回复哦!

需要的外包支持:

          mp3spi1.9.4.jar  、 jmf.jar  、 jgoodies-forms-1.8.0-sources.jar  、  jaudiotagger-2.0.3.jar  、jl1.0.jar   (点击即可下载)

外包下载后只需要加到   “引用的库” 中 即可 。

package player;

import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Label;
import java.awt.List;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.border.EmptyBorder;
import javazoom.jl.decoder.Bitstream;
import javazoom.jl.decoder.BitstreamException;
import javazoom.jl.decoder.Header;

public class Player extends JFrame{
	
	private JButton backplay,frontplay, play,stop,openMusic,online;

	private Label MusicName;
	private JProgressBar timeJProgressBar;
	private JLabel Start;
	private JLabel Endtime ;
	private JPanel contentPane;
	private JTextArea textArea;
	private JPopupMenu popupMenu;
	private JMenuItem items[];

	private JRadioButton selfPlay,liebiao,suiji;
	private ButtonGroup radiobutton;
	
	
	
	String filepath;// 播放文件目录
	String filename;// 播放文件名称
	
	AudioInputStream audioInputStream;// 文件流
	AudioFormat audioFormat;// 文件格式
	SourceDataLine sourceDataLine;// 输出设备
	 
	List list;// 文件列表
	JLabel labelfilepath;//播放目录显示标签

	boolean isStop = true;// 控制播放线程
    boolean hasStop = true;// 播放线程状态
    int n;//用于切换上一首下一首
    int max;//获取歌曲列表的最大下标
    int a=0;
	
	
	public Player(){
		
		Color color=new Color(187,255,255);
		
		
		//设置主面板样式
		setIconImage(Toolkit.getDefaultToolkit().getImage(Player.class.getResource("/images/titleico.png")));
		setTitle("\u8FF7\u4F60\u97F3\u4E50\u64AD\u653E\u5668");
		
		Toolkit toolkit=Toolkit.getDefaultToolkit();
		Dimension dimension=toolkit.getScreenSize();
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds((dimension.width-660)/2, (dimension.height-479)/2, 660, 479);
		this.setResizable(false);
		
		//添加组件,并定位
		//添加 jpanel
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setBackground(color);
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		//歌曲名称
		MusicName=new Label("MusicName");
		
		MusicName.setBounds(14, 23, 500, 18);
		contentPane.add(MusicName);
		
		
		//存储路径
		labelfilepath=new JLabel();
		labelfilepath.setBounds(310, 68, 500, 18);
		contentPane.add(labelfilepath);
		
		
		//播放进度
		timeJProgressBar=new JProgressBar();
		
		timeJProgressBar.setBounds(24, 54, 263, 7);
		contentPane.add(timeJProgressBar);
		
		
		//播放时间
		Start = new JLabel("00:00");
		Start.setBounds(24, 62, 46, 18);
		contentPane.add(Start);
		
		Endtime = new JLabel("00:00");
		Endtime.setBounds(260, 62, 46, 18);
		contentPane.add(Endtime);
		
		//按钮组件
		backplay = new JButton("");
		backplay.setIcon(new ImageIcon(Player.class.getResource("/images/back.png")));
		backplay.setBounds(24, 93, 38, 30);
		contentPane.add(backplay);
		
		
		play = new JButton("");
		play.setIcon(new ImageIcon(Player.class.getResource("/images/play.png")));
		play.setBounds(76, 93, 38, 30);
		contentPane.add(play);
		
		stop=new JButton("");
		stop.setIcon(new ImageIcon(Player.class.getResource("/images/app.png")));
		stop.setBounds(128, 93, 38, 30);
		contentPane.add(stop);
		
		frontplay = new JButton("");
		frontplay.setIcon(new ImageIcon(Player.class.getResource("/images/front.png")));
		frontplay.setBounds(180, 93, 38, 30);
		contentPane.add(frontplay);

		//创建列表
		list = new List(10);
        list.setBounds(24, 163, 270, 250);
        contentPane.add(list);
        
        
        
        //播放模式
        selfPlay=new JRadioButton("单曲循环", true);
        selfPlay.setBounds(380, 335, 100, 20);
        selfPlay.setBackground(color);
        contentPane.add(selfPlay);
        
        liebiao=new JRadioButton("列表循环", false);
        liebiao.setBounds(490, 335, 100, 20);
        liebiao.setBackground(color);
        contentPane.add(liebiao);
        
        
        radiobutton=new ButtonGroup();
        radiobutton.add(liebiao);
        radiobutton.add(selfPlay);
        
     
        
        //弹出式菜单
        popupMenu=new JPopupMenu();
        items=new JMenuItem[4];
        items[0]=new JMenuItem("添加歌曲");
        items[1]=new JMenuItem("播放歌曲");
        items[2]=new JMenuItem("删除选中歌曲");
        items[3]=new JMenuItem("清空列表");
        for (int i = 0; i < items.length; i++) { popupMenu.add(items[i]); items[i].addActionListener(new popupMenuListener()); } textArea=new JTextArea(); textArea.setBounds(308, 85, 300, 18); textArea.setBackground(color); textArea.setEditable(false); contentPane.add(textArea); openMusic=new JButton("添加音乐"); openMusic.setBounds(350, 370, 100, 40); contentPane.add(openMusic); online=new JButton("在线听歌"); online.setBounds(480, 370, 100, 40); contentPane.add(online); backplay.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { // 点击时处理 if (e.getClickCount() == 1) { // 播放上一首 if (filename==null) { JOptionPane.showMessageDialog(null, "未选择歌曲!"); } else { if (n>0) {
							filename = list.getItem(n-1);
							n--;       //
							play();timeBar();
						} else {
							max=list.getItemCount();
							filename = list.getItem(max-1);
							n=max-1;
							play();timeBar();
						}
					}
                	
                }
			}
			
		});
        
        
        play.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                // 点击时处理
                if (e.getClickCount() == 1) {
                    // 播放选中的文件
                    filename = list.getSelectedItem();
                   
                    if (filename==null) {
						JOptionPane.showMessageDialog(null, "未选择歌曲!");
					} else {
						
	                    play();timeBar();
					}
                }
                
            }
        });
		
        
        stop.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                // 点击时处理
                if (e.getClickCount() == 1) {
                    // 停止播放
                    isStop=true;
                    hasStop=true;
                    textArea.setText("已停止播放      "+filename);
                    
                    
                }
            }
        });
        
        

		frontplay.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
                // 点击时处理
				
                if (e.getClickCount() == 1) {
                    // 播放下一首
                	if (filename==null) {
						JOptionPane.showMessageDialog(null, "未选择歌曲!");
					} else {
						
						max=list.getItemCount();
						if (n==max-1) {
							filename=list.getItem(0);
							n=0;
							play();timeBar();
						} else {
							filename = list.getItem(n+1);
							n++;
							play();timeBar();
						}
					}
                
                }
			}
			
		});
		
        
        
        list.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                // 双击时处理
                if (e.getClickCount() == 2) {
                    // 播放选中的文件
                    filename = list.getSelectedItem();
                    
                    if (filename==null) {
						JOptionPane.showMessageDialog(null, "未选中,无法播放");
						textArea.setText("未选中,无法播放");
					}else{
						n=list.getSelectedIndex();//获取
                    play();timeBar();
                
					}
                }
            }

			@Override
			public void mousePressed(MouseEvent arg0) {
				checkForTriggerEvent(arg0);
			}

			@Override
			public void mouseReleased(MouseEvent arg0) {
				checkForTriggerEvent(arg0);
			}
			
			public void checkForTriggerEvent(MouseEvent event){           //方法学于书本  P516
				if(event.isPopupTrigger()){
					popupMenu.show(event.getComponent(), event.getX(), event.getY());
				}
				
			}
        });
        
        
        openMusic.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				open();
				
			}
		});
        
        
        online.addMouseListener(new MouseAdapter() {

			@Override
			public void mouseClicked(MouseEvent e) {
				try {
					URI website=new URI("http://music.baidu.com/top");
					Desktop desktop=Desktop.getDesktop();
					if (Desktop.isDesktopSupported()&&desktop.isSupported(Desktop.Action.BROWSE)) {
						desktop.browse(website);
					}
				} catch (MalformedURLException e1) {
					// TODO 自动生成的 catch 块
					e1.printStackTrace();
				} catch (IOException e1) {
					// TODO 自动生成的 catch 块
					e1.printStackTrace();
				} catch (URISyntaxException e1) {
					// TODO 自动生成的 catch 块
					e1.printStackTrace();
				}
				
			}
        	
		});
		
		this.setVisible(true);
	}
	   private void open() {
		   
	        FileDialog dialog = new FileDialog(this, "Open", 0);
	       
	        dialog.setFilenameFilter(new FilenameFilter() {
				
				@Override
				public boolean accept(File dir, String name) {
					
					return name.endsWith(".mp3")||name.endsWith(".mid")||name.endsWith(".wav");
				}
			});
	        dialog.setVisible(true);
	        filepath = dialog.getDirectory();
	        if (filepath != null) {
	        	
	            labelfilepath.setText("目录:" + filepath);
	 
	            // 显示文件列表
	            list.removeAll();
	            File filedir = new File(filepath);
	            File[] filelist = filedir.listFiles();
	            for (File file : filelist) {
	                String filename = file.getName().toLowerCase();
	                if (filename.endsWith(".mp3") || filename.endsWith(".wav")) {
	                    list.add(filename);
	                }
	            }
	        }
	    }
	
	   
	   //获取时间
	   public static String getAudioPlayTime(String filePath){
		   	
	        FileInputStream stream;
	        int time = 0;
	        try {
	            stream = new FileInputStream(new File(filePath));
	            int b = stream.available();
	            Bitstream bt = new Bitstream(stream);
	            Header h = bt.readFrame();
	            time = (int) h.total_ms(b);
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } catch (BitstreamException e) {
	            e.printStackTrace();
	        }
	        int i = time/1000; //s
	        int m = i/60;
	        int s = i%60;
	        
//	        System.out.println("mp3 时长为:"+i+"s");
	        String longtime=new String(m+":"+s);
	        return longtime;
	        
	    }
	   //自定义进度条的方法
	   private void timeBar(){
		   programThread gramthread=new programThread();
           gramthread.start();
           
		   
	   }
	   
	   //定义播放的方法
	   private void play() {
	        try {
	            isStop = true;// 停止播放线程
	            // 等待播放线程停止
	            
	            
	            
	            textArea.setEditable(true);
	            textArea.setText("正在播放:" + filename+"\n");//状态栏显示播放情况
	            textArea.setEditable(false);
	            
	            
	            while (!hasStop) {
	            	
	                try {
	                    Thread.sleep(10);
	                } catch (Exception e) {
	                }
	            }
	            			//换行操作
	            File file = new File(filepath + filename);
	            MusicName.setText("歌曲名称:" + filename);
	           
	            // 取得文件输入流
	            audioInputStream = AudioSystem.getAudioInputStream(file);
	            audioFormat = audioInputStream.getFormat();
	            
	            //获取歌曲时长
	            String time= getAudioPlayTime(filepath+filename);
	            Endtime.setText(time);
	            
	           
	            // 转换 mp3 文件编码
	            if (audioFormat.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
	                audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
	                        audioFormat.getSampleRate(), 16, audioFormat
	                                .getChannels(), audioFormat.getChannels() * 2,
	                        audioFormat.getSampleRate(), false);
	                audioInputStream = AudioSystem.getAudioInputStream(audioFormat,
	                        audioInputStream);
	            }
	            
	 
	            // 打开输出设备
	            DataLine.Info dataLineInfo = new DataLine.Info(
	                    SourceDataLine.class, audioFormat,
	                    AudioSystem.NOT_SPECIFIED);
	            sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
	            
	            sourceDataLine.open(audioFormat);
	            sourceDataLine.start();
	            
	 
	           
	            // 创建独立线程进行播放
	            isStop = false;
	            Thread playThread = new Thread(new PlayThread());
	          
//	            programThread gramthread=new programThread();
//	            gramthread.start();
	            playThread.start();
	            
	            
          
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        
	    }
	   
	 
	   class PlayThread extends Thread {
		    byte tempBuffer[] = new byte[320];
		 
		    public void run() {
		        try {
		            int cnt;
		            hasStop = false;
		            
		            // 读取数据到缓存数据
		            while ((cnt = audioInputStream.read(tempBuffer, 0,
		                    tempBuffer.length)) != -1) {
		                if (isStop){
		                    break;
		                }
		                if (cnt > 0) {
		                    // 写入缓存数据
		                    sourceDataLine.write(tempBuffer, 0, cnt);
		                }
		            }
		            // Block 等待临时数据被输出为空
		            sourceDataLine.drain();
		            sourceDataLine.close();
		            hasStop = true;
		        } catch (Exception e) {
		            e.printStackTrace();
		            System.exit(0);
		        }
		    }
		}
	   class xunhuan extends Thread {

		@Override
		public void run() {
  
			if (a==0) {
				
				if (selfPlay.isSelected()) {
					filename = list.getItem(n);
					play();
				}
				if (liebiao.isSelected()) {
					max=list.getItemCount();
					if (n==max-1) {
						filename=list.getItem(0);
						n=0;
						play();timeBar();
					} else {
						filename = list.getItem(n+1);
						n++;
						play();
					}
				}
				
			}
			super.run();
		}
  
	   }
	   
	   public static int programTime(String filePath){
		   	
	        FileInputStream stream;
	        int time = 0;
	        try {
	            stream = new FileInputStream(new File(filePath));
	            int b = stream.available();
	            Bitstream bt = new Bitstream(stream);
	            Header h = bt.readFrame();
	            time = (int) h.total_ms(b);
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        } catch (BitstreamException e) {
	            e.printStackTrace();
	        }
	        int i = time/1000; //s
	        return i;
	        
	    }
	   
	   //进度条,还是不流畅,一步一步的走
 class programThread extends Thread{
	 
	 	Timer timer=new Timer(1000, new ActionListener() {
			
	 			@Override
	 				public void actionPerformed(ActionEvent e) {
	 					a++;
				
	 				}
	 	});
	 	
	 		
		   int ptime=programTime(filepath+filename);
		   
		   
		   public void run(){
			   timeJProgressBar.setMinimum(0);
			   timeJProgressBar.setMaximum(ptime);
			   timeJProgressBar.setValue(0);
			   
			   timer.start();
			   
			   while (a<ptime) {
	                
	                timeJProgressBar.setValue(a);
	                int m=a/60;
	                int s=a%60;
	                if (m<9) {
						if (s<=9) { String start=new String("0"+m+":0"+s); Start.setText(start); } if (s>9) {
							String start=new String("0"+m+":"+s);
							Start.setText(start);
						}
					}
	                if (m>9) {
	                	if (s<=9) { String start=new String(m+":0"+s); Start.setText(start); } if (s>9) {
							String start=new String(m+":"+s);
							Start.setText(start);
						}
					}
	                
	                if (isStop){
	                	timer.stop();
	                	a=0;
	                    break;
	                }
	            }
			   timer.stop();
			   a=0;
			   timeJProgressBar.setValue(a);
			  
			   Start.setText("00:00");
			   
			   xunhuan name=new xunhuan();
	           name.start();
		   }
		   
	   }
 		class popupMenuListener implements ActionListener  {

			@Override
			public void actionPerformed(ActionEvent e) {
				if (e.getSource()==items[0]) {
					open();
				}
				if (e.getSource()==items[1]) {
					 	filename = list.getSelectedItem();
	                   
	                    if (filename==null) {
							JOptionPane.showMessageDialog(null, "未选择歌曲!");
						} else {
							
		                    play();
						}
				}
				if (e.getSource()==items[2]) {
						filename = list.getSelectedItem();
	                   
	                    if (filename==null) {
							JOptionPane.showMessageDialog(null, "未选择歌曲!");
						} else {
							list.remove(filename);
						}
				}
				if (e.getSource()==items[3]) {
					int n=list.getItemCount();
                    if (n==0) {
						JOptionPane.showMessageDialog(null, "不需要清空");
					} else {
						list.removeAll();
					}
			}
				
			}
 			
 		}
 		
 		
	   
	public static void main(String[] args) {
		Player player=new Player();
		
	}

}

    感觉不错,留个言顶一下吧!有问题可以通过留言提问哦,如果觉得博主很良心的话,可以在下方“赏”的地方投个币哦~!


TeenShare 梯云分享 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明JAVA 编写的迷你音乐播放器
喜欢 (8)
[欢迎投币]
分享 (0)
关于作者:
一个整天无所事事的,有时候忽然热血的孩子
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址