注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

蓝星天宇

爱生活,爱分享!

 
 
 

日志

 
 

新宇Java音乐播放器【课程设计】  

2009-12-28 14:52:30|  分类: 计算机编程类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

一、主界面

新宇Java音乐播放器【课程设计】 - 蓝宇天奇 - 蓝宇翱翔的博客

二、打开文件

新宇Java音乐播放器【课程设计】 - 蓝宇天奇 - 蓝宇翱翔的博客

三、播放测试

新宇Java音乐播放器【课程设计】 - 蓝宇天奇 - 蓝宇翱翔的博客

四、酷狗格式转换器(帮助)

新宇Java音乐播放器【课程设计】 - 蓝宇天奇 - 蓝宇翱翔的博客

五、源代码--附:完全注释

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;//用于打开指定格式文件设置 JFileChooser
import javax.swing.border.*;
import javax.swing.event.*;
import javax.media.*;
import javax.media.bean.playerbean.MediaPlayer;
import java.net.URL;
import java.util.List;
import java.util.ArrayList;

public class MusicPlayer  extends JFrame implements ActionListener,ChangeListener
{
 //////////////////////////////
    JMenu jfile=new JMenu("文件(F)");
    //////////////////////////////
    JMenu jhelp=new JMenu("帮助(S)"); 
    /////////////////////////////
    JMenu jFormat=new JMenu("工具(T)");
    /////////////////////////////
 JMenuItem jOpen=new JMenuItem("打开(O)",new ImageIcon("open.png"));
    JMenuItem jClose=new JMenuItem("退出",new ImageIcon("exit.png"));
    ////////////////////////////
    JMenuItem jHelp=new JMenuItem("帮助(H)",new ImageIcon("help.png"));
    JMenuItem jAbout=new JMenuItem("关于",new ImageIcon("about.png"));
    ///////////////////////////
    JMenuItem jChange=new JMenuItem("酷狗(K)",new ImageIcon("kugou.png"));
    ///////////////////////////
    //存放音乐文件的具体路径
    //提供"接口" 添加音乐列表 只需修改此处路径
    //private static final String AUDIO_DIR ="MyMusic"+"\\";
    //private static final String AUDIO_DIR ="D:\\Music"+"\\";
    private static final String AUDIO_DIR ="F:\\Kugou"+"\\";
    //////////////////////////
    static JList fileList;//播放文件列表申明
    static ExpAudioPlayer player=null;
     //////////////////功能按钮定义
        JButton prev=new JButton(new ImageIcon("prev.png"));
        JButton play=new JButton(new ImageIcon("play.png"));
        JButton pause=new JButton(new ImageIcon("pause.png"));
        JButton next=new JButton(new ImageIcon("next.png"));
        JButton stop=new JButton(new ImageIcon("stop.png"));
     //////////////////  
     static JSlider slider;//进度条
     ///////////////////////
     static TitledBorder border;//进度条容器标题
     ////////////////////
     JMenuBar jbar=new JMenuBar();  
     ///////////////////
     ///////////////////
     JPanel backImage=new JPanel(new BorderLayout(8,8));
     //////////////////////////
     JPanel p1=new JPanel(new GridLayout(1,5));//按钮存放的容器
     /////////////////////////
     static File music;
     ///////////////
     static Thread t;//线程声明
     /////////////
     static boolean state=false;//标记播放状态
     /////////////
     static String prfilename="";//第一次播放的文件名
     /////////////
     static int selectedIndex=0; //用于保存当前所选歌曲索引
     /////////////
     static String abstractPath="";//用于保存当前文件相对路径
     //////////////
     ///////////////
     static int maxtime=0;//设置保存音乐文件的持续时间
     //////////////
     String[] audioFileNames = findFiles(AUDIO_DIR,".mp3");//文件格式筛选,限定mp3音频格式
 MusicPlayer(String s)
    {
     super(s);
       jOpen.setAccelerator(KeyStroke.getKeyStroke('O',java.awt.event.InputEvent.CTRL_DOWN_MASK));
       jfile.add(jOpen);
       jOpen.addActionListener(this);
       jfile.addSeparator();
       jfile.add(jClose);
       jClose.addActionListener(this);
       jHelp.setAccelerator(KeyStroke.getKeyStroke('H',java.awt.event.InputEvent.CTRL_DOWN_MASK));
       jhelp.add(jHelp);
       jhelp.addSeparator();
       jhelp.add(jAbout);
       jChange.addActionListener(this);
       jChange.setAccelerator(KeyStroke.getKeyStroke('K',java.awt.event.InputEvent.CTRL_DOWN_MASK));
       jFormat.add(jChange);
       ////////////////////////////
       prev.setBackground(Color.black);
       play.setBackground(Color.black);
       pause.setBackground(Color.black);
       next.setBackground(Color.black);
       stop.setBackground(Color.black);
        ////////////////////////////
        jbar.setBackground(Color.LIGHT_GRAY);
       jbar.add(jfile);
       jbar.add(jhelp);
       jbar.add(jFormat);
       ///////////////////////////
       this.setJMenuBar(jbar);
       this.setResizable(false);//禁止调整窗体大小
        ///////////////////////////
      
        //////////////////////////
        play.addActionListener(this);//播放 事件侦听
        pause.addActionListener(this);//暂停
        stop.addActionListener(this);//停止
        prev.addActionListener(this);//上一曲
        next.addActionListener(this);//下一曲
        jHelp.addActionListener(this);//帮助 跳转至 我的网易博客
        jAbout.addActionListener(this);//程序简介
        p1.add(prev,BorderLayout.NORTH);p1.add(play,BorderLayout.NORTH);p1.add(pause,BorderLayout.NORTH); p1.add(next,BorderLayout.NORTH);p1.add(stop,BorderLayout.NORTH);this.add(p1,BorderLayout.NORTH);
        //////////////////////////
        this.addWindowListener(new WinHandel());//关闭程序
        //////////////////////////
       JPanel progress=new JPanel(new GridLayout(1,1,10,10));//天加用于显示当前音乐播放进度和时间的组件
       {
      slider= new JSlider(0,600, 0);
      border= new TitledBorder("歌曲时间:00:00:00");
        border.setTitleColor(Color.CYAN);
        slider.setBorder(new CompoundBorder(new EmptyBorder(0,0,0,0),border));
        slider.addChangeListener(this);
        slider.setBackground(Color.BLACK);
        slider.setMajorTickSpacing(25);
        slider.setPaintTicks(true);
        progress.add(slider);
        this.add(progress,BorderLayout.PAGE_END);
       }
        this.setBackground(Color.black);
        //////////////////////////
        this.setBounds(200,200,400,300);
        this.setVisible(true);
        //////////////////////////
        makeList(audioFileNames);//已经创建音乐播放列表实例
        /////////////////////////
    }
 public static void main(String args[])throws ArrayIndexOutOfBoundsException
    {
     new MusicPlayer("编程081班Java第五组--音乐播放器");
     //////////////////////////
     /////////////////////////
        fileList.addMouseListener//鼠标双击事件
        (
          new MouseAdapter()
          {
           public void mouseClicked(MouseEvent e)
           {
          try
          {
           if(e.getClickCount()>=1 && e.getButton()==MouseEvent.BUTTON1)//双击的时候执行播放 并且是 左键
               {
                slider.setValue(0);
               if(t!=null)
               {
              t.stop();
               }
                int index=fileList.locationToIndex(e.getPoint());
                fileList.setSelectedIndex(index);
                selectedIndex=fileList.getSelectedIndex();
               String filename=(String)fileList.getSelectedValue();
                        if(filename == null)
                        { 
                          return;
                        }
                        else
                        {
                         if(state==false && !prfilename.equals(filename))
                         {
                             prfilename=filename;
                          music=new File(AUDIO_DIR+filename);
                          player=new ExpAudioPlayer(music);
                          player.play();state=true;
                                t=new Thread(new Runnable()
                          {
                         public void run()
                          {
                           int time=0;maxtime=player.getTotalTime();//获取歌曲最大时间
                           slider.setMaximum(maxtime);//重新设置进度条长度为最大歌曲时间 以保证进度到了顶端 歌曲停止
                        while(time<=maxtime)
                        {
                      try
                       {
                       Thread.sleep(1000);
                       ++time;
                       border.setTitle("歌曲时间:"+ExpAudioPlayer.secondsToTime(time));
                       slider.setValue(time);
                       }
                       catch(Exception e){};         
                       }
                        }
                                  });
                           t.start(); 
                         }
                         else
                         {
                          player.stop();state=false;prfilename="";
                         }
                        }
                        //System.out.print(index);//输出选择的索引值 验证结果
                        //System.out.print((Time)player.getDuration());
                        System.out.println("正在播放:"+prfilename+"  歌曲时间:  "+ExpAudioPlayer.secondsToTime(player.getTotalTime()));//获取歌曲总时间
               }
          }
          catch(Exception ex){System.out.print("");}
          }
          } 
        );
    }
 private void makeList(String[] audioFiles)
    {
     fileList=new JList(audioFiles);
     JScrollPane scrollPane = new JScrollPane(fileList);
     fileList.setBackground(Color.black);
     fileList.setFont(new Font("宋体",Font.PLAIN,13));//设置字体 界面优化
     fileList.setForeground(Color.cyan);
     backImage.add(scrollPane,BorderLayout.PAGE_START);
     ///////////////////////////添加背景图片
     JLabel image = new JLabel(new ImageIcon("Background.jpg"));
        backImage.add(image, BorderLayout.CENTER);
        backImage.setBackground(Color.black);
     this.add(backImage);
     fileList.setFocusable(true);
     ////////////////////////////////

    }//添加文件到列表
 private String[] findFiles(String dirName, String suffix)
    {
        File dir = new File(dirName);
        if(dir.isDirectory())
         {
              String[] allFiles = dir.list();
              if(suffix == null)
              {
               return allFiles;
              }
             else
             {
                      List<String> selected = new ArrayList<String>();
                      for(String filename : allFiles)
                       {
                           if(filename.endsWith(suffix))
                            {
                               selected.add(filename);
                            }
                        }
                return selected.toArray(new String[selected.size()]);
            }
        }
        else {
            System.out.println("错误提示:" + dirName + "必须存在此路径!");
            return null;
        }
    }
 public synchronized void actionPerformed(ActionEvent e)//相关事件处理
 {
    ////////////////按钮事件定义
          if(e.getSource().equals(jOpen))
          {
           try
           {
            if(player==null && state==false)
            {
               if(t!=null)
               {
              t.stop();
               }
             ////////////////////////////////////
                JFileChooser chooser = new JFileChooser();
                         FileNameExtensionFilter filter = new FileNameExtensionFilter("mp3","MP3");
                         chooser.setFileFilter(filter);
                         int returnVal = chooser.showOpenDialog(this);
                         if(returnVal == JFileChooser.APPROVE_OPTION)
                         {
                             //System.out.println("You chose to open this file: " +chooser.getSelectedFile().getCanonicalFile()+chooser.getSelectedFile().getName());
                             String filename=chooser.getSelectedFile().getCanonicalFile().toString().trim();
                             if(state==false && !prfilename.equals(filename))
                       {  
                          slider.setValue(0);   
                             prfilename=filename;
                             music=new File(filename);
                             player=new ExpAudioPlayer(music);
                             player.play();state=true;
                             t=new Thread(new Runnable()
                             {
                            public void run()
                            { 
                              int time=0;
                              maxtime=player.getTotalTime();
                              slider.setMaximum(maxtime);
                           while(time<=maxtime)
                           {
                         try
                         {
                       Thread.sleep(1000);
                       ++time;
                       border.setTitle("歌曲时间:"+ExpAudioPlayer.secondsToTime(time));
                       slider.setValue(time);
                         }
                       catch(Exception e){}             
                            }
                           }
                              });
                           t.start(); 
                       } 
                   else
                       {
                       player.stop();state=false;prfilename="";if(t!=null){t.stop();}
                       }
                         }
             ////////////////////////////////////
            }
              System.out.println("正在播放:"+prfilename+"  歌曲时间:  "+ExpAudioPlayer.secondsToTime(player.getTotalTime()));//获取歌曲总时间
           }
                    catch(Exception e1){player=null;state=false;}
          }
          else if(e.getSource().equals(jClose)) 
          {
             System.exit(0);
          }
          else if(e.getSource().equals(play))//播放
          {
           try
           {
            if(t!=null)
               {
               t.stop();
               }
            String filename=(String)fileList.getSelectedValue();
                  selectedIndex=fileList.getSelectedIndex();
                        if(filename == null)
                        { 
                          return;
                        }
                        else
                        {
                         slider.setValue(0);
                         if(state==false && !prfilename.equals(filename))
                         {
                             prfilename=filename;
                          music=new File(AUDIO_DIR+filename);
                          player=new ExpAudioPlayer(music);
                          player.play();state=true;
                          t=new Thread(new Runnable()
                             {
                            public void run()
                            { 
                              int time=0;
                              maxtime=player.getTotalTime();
                              slider.setMaximum(maxtime);
                           while(time<=maxtime)
                           {
                         try
                         {
                       Thread.sleep(1000);
                       ++time;
                       border.setTitle("歌曲时间:"+ExpAudioPlayer.secondsToTime(time));
                       slider.setValue(time);
                         }
                       catch(Exception e){}             
                            }
                           }
                              });
                           t.start(); 
                         }
                         else
                         {
                          player.stop();state=false;prfilename="";if(t!=null){t.stop();}slider.setValue(0);
                         }
                        }
                        play.setFocusable(false);
                        System.out.println("正在播放:"+prfilename+"  歌曲时间:  "+ExpAudioPlayer.secondsToTime(player.getTotalTime()));//获取歌曲总时间
           }
                    catch(Exception e2){player=null;state=false;}
          }
          else if(e.getSource().equals(pause))//暂停
          {
           try
           {
             if(player!=null && t!=null)
             {
              //player.pause();
               pause.setFocusable(false);
               //t.stop();
             }
                    }
           catch(Exception e2){System.out.println("已经暂停!");}
          }  
          else if(e.getSource().equals(stop))//停止
          {
           try
           {
            player.stop();player=null;state=false;prfilename="";stop.setFocusable(false);border.setTitle("歌曲时间:00:00:00");if(t!=null){t.stop();}slider.setValue(0);
           }
           catch(Exception e5){System.out.println("已经停止!");player=null;state=false;}
          }
          else if(e.getSource().equals(jHelp))
          {
              String cmdStr = "explorer
http://besttianqi.blog.163.com/";
               try {
                    Runtime.getRuntime().exec(cmdStr);
                   } catch (IOException ex){System.out.print("跳转至My Blog!");}
          }
          else if(e.getSource().equals(jAbout))
          {
           JOptionPane.showMessageDialog(this, "<html><h4>JAVA音乐播放器\n" +"<html><h4>编程081班 Java第五小组\n" +"<html><h4>Email:
Besttianqi@163.com\n"+"<html><h4>特别鸣谢:彭老师给予的技术支持!",
                    "关于",JOptionPane.INFORMATION_MESSAGE);
          }
          else if(e.getSource().equals(prev))//上一曲
          {
           try
           {
           if(t!=null){t.stop();}
           if(player!=null && state!=false)
           {
             player.stop();player=null;state=false;
           }
           else
           {
            fileList.setSelectedIndex(--selectedIndex);
            int prevs=fileList.getSelectedIndex();
            if(prevs>=0)//最小索引值
            {
               String filename=(String)fileList.getSelectedValue();
                  selectedIndex=fileList.getSelectedIndex();
                        if(filename == null)
                        { 
                          return;
                        }
                        else
                        {
                         if(state==false)
                         {
                          slider.setValue(0);
                             prfilename=filename;
                          music=new File(AUDIO_DIR+filename);
                          player=new ExpAudioPlayer(music);
                          player.play();state=true;
                          t=new Thread(new Runnable()
                             {
                            public void run()
                            { 
                              int time=0;
                              maxtime=player.getTotalTime();
                              slider.setMaximum(maxtime);
                           while(time<=maxtime)
                           {
                         try
                         {
                       Thread.sleep(1000);
                       ++time;
                       border.setTitle("歌曲时间:"+ExpAudioPlayer.secondsToTime(time));
                       slider.setValue(time);
                         }
                       catch(Exception e){}             
                            }
                           }
                              });
                           t.start();  
                         }
                         else
                         {
                          player.stop();
                          if(t!=null){t.stop();}
                          state=false;t.stop();
                          slider.setValue(0);
                         }
                        } 
             }
           }
           prev.setFocusable(false);
           System.out.println("正在播放:"+prfilename+"  歌曲时间:  "+ExpAudioPlayer.secondsToTime(player.getTotalTime()));
            }
                  catch(Exception e3){player=null;state=false;}
          }
          else if(e.getSource().equals(next))//下一曲
          {
           try
           {
           if(t!=null){t.stop();}
           if(player!=null && state!=false)
           {
             player.stop();player=null;state=false;
           }
           else
           {
             fileList.setSelectedIndex(++selectedIndex);
             int nexts=fileList.getSelectedIndex();
             if(nexts<=1000)//最大索引值
             {
               String filename=(String)fileList.getSelectedValue();
                  selectedIndex=fileList.getSelectedIndex();
                        if(filename == null)
                        { 
                          return;
                        }
                        else
                        {
                         if(state==false)
                         {
                          slider.setValue(0);
                             prfilename=filename;
                          music=new File(AUDIO_DIR+filename);
                          player=new ExpAudioPlayer(music);
                          player.play();state=true;
                          t=new Thread(new Runnable()
                             {
                            public void run()
                            { 
                              int time=0;
                              maxtime=player.getTotalTime();
                              slider.setMaximum(maxtime);
                           while(time<=maxtime)
                           {
                         try
                         {
                       Thread.sleep(1000);
                       ++time;
                       border.setTitle("歌曲时间:"+ExpAudioPlayer.secondsToTime(time));
                       slider.setValue(time);
                         }
                       catch(Exception e){}             
                            }
                           }
                              });
                       t.start();  
                         }
                         else
                         {
                          player.stop();state=false;t.stop();slider.setValue(0);if(t!=null){t.stop();}
                         }
                        }
           }
           next.setFocusable(false);
            }
           System.out.println("正在播放:"+prfilename+"  歌曲时间:  "+ExpAudioPlayer.secondsToTime(player.getTotalTime()));  
           }
          catch(Exception e4){player=null;state=false;}
          }
          else if(e.getSource().equals(jChange))//打开存放在相对路径下的酷狗格式转换器 一个小时提取出来的
          {
           try {
                 abstractPath=(new File(".")).getCanonicalPath()+"\\酷狗音乐转换器
\\Encode.exe";//System.out.print(abstractPath);
                 String cmdStr = abstractPath;
                 Runtime.getRuntime().exec(cmdStr);
                   } catch (IOException ex){System.out.print("酷狗音乐2010!");}
          }
          else
          {
           return;
          } 
 } 
 public synchronized void stateChanged(ChangeEvent e)//获取与设置当前播放进度
 {
  
 }        
}
class ExpAudioPlayer extends MediaPlayer
{
 private Player audioPlayer;
 private int currentSoundFrameLength = 0;
 public ExpAudioPlayer(URL url) throws IOException,NoPlayerException,CannotRealizeException
 {
   audioPlayer = Manager.createRealizedPlayer(url);
  
 }
 public ExpAudioPlayer(File file) throws IOException,NoPlayerException,CannotRealizeException
 {
  this(file.toURL());
 }
 /*public ExpAudioPlayer(String filename)throws IOException,NoPlayerException,CannotRealizeException
 {
   this(new File(filename));
 }*/
 public ExpAudioPlayer(String filepath) throws IOException,NoPlayerException,CannotRealizeException
 {
   audioPlayer= Manager.createPlayer(new MediaLocator(filepath));
 }
 //获得曲目的总时间
 public int getTotalTime()
 {
  Time t=audioPlayer.getDuration();
  int l=(int)(t.getSeconds());
  return l;
 }
 //播放
 public void play()
 {
  if(audioPlayer!=null)
  {
   audioPlayer.start();
  }
 }
 //停止播放
 public void stop()
 {
  if(audioPlayer!= null)
  {
     audioPlayer.stop();
       audioPlayer.close();
       audioPlayer=null;
  }
 }
 public void pause()
 {
  if(audioPlayer!= null)
  {
   audioPlayer.stop();
  }
 }
public static String secondsToTime(int seconds)//秒转换为时间格式算法
{
    int minutes = 0;
    int hours = 0;
 while( seconds >= 60 )
    {
       minutes += 1;
       seconds -= 60;
    }
    while( minutes >= 60)
    {
     hours += 1;
     minutes -= 60;
    }
    String strHours =Integer.toString(hours);
    String strMinutes = Integer.toString(minutes);
    String strSeconds = Integer.toString(seconds);
    if(strHours.length()<2)
    strHours = "0" + strHours;
    if(strMinutes.length()<2)
    strMinutes = "0" + strMinutes;
    if(strSeconds.length()<2)
    strSeconds = "0" + strSeconds;
    String str=strHours+":"+strMinutes+":"+strSeconds;
    return str;
}
}
//继承 WindowAdapter 设置程序关闭
class WinHandel extends WindowAdapter
{
 public void windowClosing(WindowEvent winevnet)
 {
    System.exit(0);
 }
}

 

  评论这张
 
阅读(532)| 评论(2)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2016