欢迎光临
我一直在奋斗

Java简易音乐播放器

首先我们要先做需求分析,了解我们该需要些什么更能,还有就是界面问题,我们需要什么样的框架。

 

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Label;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.FilePermission;
import java.net.URL;
import java.nio.channels.FileLock;
import java.time.format.FormatStyle;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.filechooser.FileNameExtensionFilter;

import java.lang.reflect.Method;
public class Music extends JFrame implements ActionListener {
	 public static AudioClip clip;
	 public String []str=new String[100];
	 public String []fileendname=new String[100];
	 public static int flag=0;
	 public static int gifnum=11;
	 File music;
	 PopupMenu popupmenu=new PopupMenu();
	 JMenuBar menuBar=new JMenuBar();
	 JMenu menu1=new JMenu("文件");
	 JMenu authormenu=new JMenu("关于");
	 JMenuItem menuopen=new JMenuItem("打开文件");
	 JMenuItem scanfile=new JMenuItem("扫描文件夹");
	 JMenuItem menuexit=new JMenuItem("退出");
	 JMenuItem introduction=new JMenuItem("作者");
	 JMenuItem mypage=new JMenuItem("我的网站");
	 MenuItem nextgif=new MenuItem("下一张图片");
	 JButton play=new JButton("播放");
	 JButton stop=new JButton("暂停");
	 JButton loop=new JButton("循环");
	 JButton nextmusic=new JButton("下一首");
	 JButton lastmusic =new JButton("上一首");
	 JPanel controlpanel=new JPanel();
	 JPanel menupanel=new JPanel();
	 JPanel leftpanel=new JPanel();
	 JPanel rightpanel=new JPanel();
	 ImageIcon image=new ImageIcon(getClass().getResource("0.gif"));
	 //ImageIcon image=new ImageIcon("");
	 JFileChooser filechoose=new JFileChooser();
	 JList musciclist=new JList(str);
	 JScrollPane scrollpane=new JScrollPane(musciclist);
	 JLabel backimage=new JLabel(image);
	 public static int i=1;
	 public static int j=1;
	public Music(String s)
	{
		
		   super(s);
		   setSize(500,500);
		   image.setImage(image.getImage().getScaledInstance(500,500,0));
		   setLayout(new BorderLayout());
		   setVisible(true);
		   controlpanel.setLayout(new GridLayout(1,4));
		   leftpanel.setLayout(new GridLayout(0,2));
		   getContentPane().add(controlpanel,BorderLayout.SOUTH);
		   getContentPane().add(menuBar,BorderLayout.NORTH);
		   getContentPane().add(leftpanel,BorderLayout.CENTER);
		   //getContentPane().add(scrollpane,BorderLayout.CENTER);
		   //getContentPane().add(musciclist,BorderLayout.CENTER);
		   //leftpanel.add(musciclist);
		   leftpanel.add(scrollpane);
		   leftpanel.add(rightpanel);
		   rightpanel.add(backimage);
		   controlpanel.add(play);
		   controlpanel.add(stop);
		   controlpanel.add(loop);
		   controlpanel.add(lastmusic);
		   controlpanel.add(nextmusic);
		   menuBar.add(menu1);
		   menuBar.add(authormenu);
		   menu1.add(menuopen);
		   menu1.add(scanfile);
		   menu1.add(menuexit);
		   popupmenu.add(nextgif);
		   authormenu.add(introduction);
		   authormenu.add(mypage);
		   add(popupmenu);
		   //scrollpane.add(musciclist);
		   play.addActionListener(this);
		   stop.addActionListener(this);
		   loop.addActionListener(this);
		   lastmusic.addActionListener(this);
		   nextmusic.addActionListener(this);
		   menuopen.addActionListener(this);
		   scanfile.addActionListener(this);
		   menuexit.addActionListener(this);
		   introduction.addActionListener(this);
		   mypage.addActionListener(this);
		   nextgif.addActionListener(this);
		   setDefaultCloseOperation(3);
			backimage.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				// TODO 自动生成的方法存根
				mouserightclick(e);
			}	
			});
		   addComponentListener(new ComponentListener() {
			
			@Override
			public void componentShown(ComponentEvent e) {
				// TODO 自动生成的方法存根
				
			}
			
			@Override
			public void componentResized(ComponentEvent e) {
				// TODO 自动生成的方法存根
				SetImageSize();
			}
			
			@Override
			public void componentMoved(ComponentEvent e) {
				// TODO 自动生成的方法存根
				
			}
			
			@Override
			public void componentHidden(ComponentEvent e) {
				// TODO 自动生成的方法存根
				
			}
		});
		  
		  /* musciclist.addListSelectionListener(new ListSelectionListener() {
				
				@Override
				public void valueChanged(ListSelectionEvent e) {
					// TODO 自动生成的方法存根
					for(int i=0;i<=flag;i++)
					
					if(musciclist.getSelectedValue()==str[i])
					{
	                       try{
						 music=new File(fileendname[i]);
					    URL url=music.toURL();
					    clip=Applet.newAudioClip(url);
	                       }catch(Exception m)
	                       {
	                    	   System.out.println("文件找不到!!"+m);
	                       }
					}
					else {
						System.out.println("点击出错了吧");
						break;
					}
				}
			});*/
		   musciclist.addMouseListener(new MouseAdapter()
		   {
			
			   @Override
			public void mouseClicked(MouseEvent e) {
				// TODO 自动生成的方法存根

					
				 if(e.getClickCount()==2)
				{
					for(int i=0;i<=flag;i++) if(musciclist.getSelectedValue()==str[i]) { try{ music=new File(fileendname[i]);//filename[]直接保存的就是文件的绝对路径 URL url=music.toURL(); clip=Applet.newAudioClip(url); clip.play(); }catch(Exception m) { System.out.println("文件找不到!!"+m); } } } if(e.getModifiers()==MouseEvent.BUTTON3_MASK) { mouserightclick(e); } } }); } public boolean judegeplaymusic() { try{ if(flag!=0) {music=new File(fileendname[0]);//filename[]直接保存的就是文件的绝对路径 URL url=music.toURL(); clip=Applet.newAudioClip(url); return true; } else{ JOptionPane.showMessageDialog(this,"没有添加文件"); return false; } }catch(Exception m) { System.out.println("请检测路径!!"+m); return false; } } public synchronized void playlastmusic() { try{ clip.stop(); if(musciclist.getSelectedIndex()-j>=0)
					{
						music=new File(fileendname[(musciclist.getSelectedIndex()-(j++))]);
						System.out.println("f1 i="+(musciclist.getSelectedIndex()-(j-1)));
						
					}
					else{
					music=new File(fileendname[flag-(Math.abs(musciclist.getSelectedIndex()-(j++))%(flag))%flag]);//filename[]直接保存的就是文件的绝对路径
					//System.out.println("f2 i="+Math.abs((musciclist.getSelectedIndex()-(j)%(flag))));
					
					}
					URL url=music.toURL();
				    clip=Applet.newAudioClip(url);
				    clip.play();
		               }catch(Exception m)
		               {
		            	   System.out.println("请检测路径!!"+m);
		               }
				
			
	}
	public void  playnextmusic()
	{
			try{
				  
				clip.stop();
				if(musciclist.getSelectedIndex()+i<=flag-1)
				{
					music=new File(fileendname[musciclist.getSelectedIndex()+(i++)]);
				//	System.out.println("f1 i="+(musciclist.getSelectedIndex()+(i)));
					
				}
				else{
				music=new File(fileendname[(musciclist.getSelectedIndex()+(i++))%(flag)]);//filename[]直接保存的就是文件的绝对路径
				//System.out.println("f2 i="+musciclist.getSelectedIndex()+(i)%(flag));
				
				}
				URL url=music.toURL();
			    clip=Applet.newAudioClip(url);
			    clip.play();
	               }catch(Exception m)
	               {
	            	   System.out.println("请检测路径!!"+m);
	               }
			
			
	}
	
	
	public static void main(String args[])
	{
		try{
		//JFrame frame=new JFrame("music player");
		Music mu=new Music("Music Player");
		mu.SetImageSize();
		//File music=new File("C:/Users/Administrator/Desktop/123.wav");
	    //URL url=music.toURL();
	    //clip=Applet.newAudioClip(url);
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
	//public void dispose()
	//{
	//  System.exit(0);
	//}
	public void  SetImageSize()
	{
		image.setImage(image.getImage().getScaledInstance(leftpanel.getWidth(),leftpanel.getHeight(),0));
		
	}
	
	public void Filescanchoose()
	{
		
		filechoose.showOpenDialog(null);  
		//File file = filechoose.getSelectedFile();
		File file=filechoose.getCurrentDirectory();
		String filestr[]=new String[100];
		filestr=file.list();
		for(int i=flag;i<flag+file.list().length;i++)
		{
			int j=0;
			str[i]=filestr[i];
			/*while(str[i].charAt(j)!='.')
				j++; 
			System.out.println(j);   去掉文件的后缀名
			str[i]=str[i].substring(0,j);*/
		}
		String abspath=file.getAbsolutePath();
				for(int i=0;i<file.list().length;i++,flag++)
				{
					//System.out.println(str[i]);
					fileendname[i]=abspath+"\\"+str[i];

				}
		//fileendname[0]=file.getPath();
				System.out.println(fileendname[1]);
		/*if(file != null)
		{
			int i=0;
			//String fileName=f.getName();
			//String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
			while(file.getName().charAt(i)!='.')
				i++;
			str[flag++]=file.getName().substring(0,i);
			fileendname[flag-1]=file.getAbsolutePath();
		}  
		*/
		musciclist.setListData(str);
		    
	}
	public void Filechoose()
	{
		filechoose.showOpenDialog(null);  
		File file = filechoose.getSelectedFile();
		//File file=filechoose.getCurrentDirectory();
		//str=file.list();
		//String abspath=file.getAbsolutePath();
		//System.out.println(file.length());
				/*for(int i=0;i<file.list().length;i++,flag++)
				{
					//System.out.println(str[i]);
					fileendname[i]=abspath+"\\"+str[i];
				}*/
		//fileendname[0]=file.getPath();
			//	System.out.println(fileendname[1]);
		if(file != null)
		{
			int i=0;
			//String fileName=f.getName();
			//String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
			while(file.getName().charAt(i)!='.')
				i++;
			System.out.println(i);
			str[flag++]=file.getName().substring(0,i);
			fileendname[flag-1]=file.getAbsolutePath();
		}  
		
		musciclist.setListData(str);
		    
	}
	public static void openURL(String url) {  
	       try {  
	           browse(url);  
	       } catch (Exception e) {  
	       }  
	   }  
	 
	   private static void browse(String url) throws Exception {  
	       //获取操作系统的名字  
	       String osName = System.getProperty("os.name", "");  
	       if (osName.startsWith("Mac OS")) {  
	           //苹果的打开方式  
	           Class fileMgr = Class.forName("com.apple.eio.FileManager");  
	           Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });  
	           openURL.invoke(null, new Object[] { url });  
	       } else if (osName.startsWith("Windows")) {  
	          //windows的打开方式。  
	           Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);  
	       } else {  
	           // Unix or Linux的打开方式  
	           String[] browsers = { "firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape" };  
	           String browser = null;  
	           for (int count = 0; count < browsers.length && browser == null; count++)  
	               //执行代码,在brower有值后跳出,  
	               //这里是如果进程创建成功了,==0是表示正常结束。  
	               if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0)  
	                   browser = browsers[count];  
	           if (browser == null)  
	               throw new Exception("Could not find web browser");  
	           else  
	               //这个值在上面已经成功的得到了一个进程。  
	               Runtime.getRuntime().exec(new String[] { browser, url });  
	       }  
	   }  


	public void actionPerformed(ActionEvent e){
		if(e.getSource()==play)
		{
			if(judegeplaymusic())
			clip.play();
		}
		if(e.getSource()==stop)
		{
			clip.stop();
		}
		if(e.getSource()==loop)
		{
			clip.loop();
		}
		if(e.getSource()==menuopen)
		{
			Filechoose();
		}
		if(e.getSource()==scanfile)
		{
			Filescanchoose();
		}
		if(e.getSource()==menuexit)
		{
			System.exit(0);
		}
		if(e.getSource()==lastmusic)
		{
			playlastmusic();
		}
		if(e.getSource()==nextmusic)
		{
			
			playnextmusic();
		}		
		if(e.getSource()==introduction)
		{
			JFrame authorframe=new JFrame("关于我");
			JTextArea authortext=new JTextArea("姓名:张柯 \n"+"学校:四川理工学院\n"+"QQ:534737859\n");
			authortext.setPreferredSize(new Dimension(100, 80));
			setDefaultCloseOperation(3);
			authorframe.add(authortext);
			authorframe.setVisible(true);
			authorframe.setSize(230,150);
			authortext.setFont(new Font(Font.SERIF,Font.BOLD, 24));
			//pack();
			authorframe.setLocationRelativeTo(null);
			authortext.setEditable(false);
		}
		if(e.getSource()==mypage)
		{
			String url=new String("www.dyhack.cn");
			openURL(url);
		}
		if(e.getSource()==nextgif)
		{
			if(i<11)
		    image=new ImageIcon(getClass().getResource((i++)+".gif"));
			else {
				i=i%11;
				image=new ImageIcon(getClass().getResource((i++)+".gif"));
				
				
			}
		    backimage.setIcon(image);
		}
		
		
	
	}
	public void mouserightclick(MouseEvent e)
	{
		int mods=e.getModifiers();
		if((mods&MouseEvent.BUTTON3_MASK)!=0)
			popupmenu.show(this,e.getX(),e.getY());
	}
	
	
	}
	


运行结果:

Music

功能还不完整,请各位多多补充。。。。。。

程序文件-百度网盘:点击这里下载

如何运行:

Win+R,输入cmd

如果文件放在C盘,就直接像我这样

openjar

请大家多多支持呀。。。

 

未经允许不得转载:奋斗者的足迹 » Java简易音乐播放器
分享到: 更多 (0)

评论 2

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  1. #1

    Happy New Year.

    wo4年前 (2016-01-01)回复
  2. #2

    看看!

    112871684年前 (2016-01-04)回复

奋斗者的足迹

联系我们加入我们