java音乐播放器实现代码
本文实例为大家分享了java音乐播放器的具体代码,供大家参考,具体内容如下
公司主营业务:成都做网站、网站建设、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联公司是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联公司推出察雅免费做网站回馈大家。
这个是源码结构介绍
这个是界面,有点简陋,见笑了,但是基本上的东西都有了,没办法,没有美工的程序写的界面
直接上源代码Player.java
package com.service; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import javax.sound.sampled.*; import javax.swing.JSlider; import javax.swing.JTable; import com.list.MusicList; import com.list.ThreadList; import com.list.ViewList; import com.model.Model; import com.model.Music; import com.view.View; /*"duration" "author" "title" "copyright" "date" "comment"*/ public class Player extends Thread{ private Player p; private long time = 0; Object lock = new Object();//一个空的对象,没什么意义 private boolean paused = false;// 暂停 继续 public boolean isPaused() { return paused; } public void setPaused(boolean paused) { this.paused = paused; } private JSlider jSliderPlayProgress;//播放进度条 private boolean over = false;//开始 结束 //是否自动播放下一曲 private boolean isNext=true; private Music music;//音乐 AudioInputStream din = null; SourceDataLine line=null; private FloatControl volume = null; private JSlider jSliderVolume; public JSlider getjSliderVolume() { return jSliderVolume; } public void setjSliderVolume(JSlider jSliderVolume) { this.jSliderVolume = jSliderVolume; } public Player(JSlider jSliderVolume,JSlider jSliderPlayProgress) { super(); this.jSliderVolume = jSliderVolume; this.jSliderPlayProgress=jSliderPlayProgress; } public Music getMusic() { return music; } public void setMusic(Music music) { this.music = music; } public FloatControl getVolume(){ return volume; } //播放音乐 public void run(){ AudioInputStream in=null; try { File file = new File(music.getPath()); //播放不了的歌曲,直接下一首,并且在音乐列表中删除 try { in = AudioSystem.getAudioInputStream(file); } catch (Exception e) { //删除有点小问题 MusicList.getList().remove(music.getId()); ViewList.getList().get(0).getJt().setModel(new Model()); nextmusic(); } AudioFormat baseFormat = in.getFormat(); AudioFormat decodedFormat = new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16, baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false); if(baseFormat.getEncoding()==AudioFormat.Encoding.PCM_UNSIGNED || baseFormat.getEncoding()==AudioFormat.Encoding.ULAW || baseFormat.getEncoding()==AudioFormat.Encoding.ALAW || baseFormat.getEncoding()==AudioFormat.Encoding.PCM_SIGNED){ time=(file.length()*8000000)/((int)(decodedFormat.getSampleRate()*baseFormat.getSampleSizeInBits())); }else{ int bitrate=0; if(baseFormat.properties().get("bitrate")!=null){ //取得播放速度(单位位每秒) bitrate=(int)((Integer)(baseFormat.properties().get("bitrate"))); if(bitrate!=0) time=(file.length()*8000000)/bitrate; } } din = AudioSystem.getAudioInputStream(decodedFormat, in); DataLine.Info info = new DataLine.Info(SourceDataLine.class, decodedFormat); line = (SourceDataLine) AudioSystem.getLine(info); line.open(); setVolume(); jSliderPlayProgress.setMaximum((int)time); jSliderPlayProgress.setValue(0); if(line!=null){ line.open(decodedFormat); byte[] data = new byte[4096]; int nBytesRead; synchronized (lock) { while ((nBytesRead = din.read(data, 0, data.length)) != -1) { while (paused) { if(line.isRunning()) { line.stop(); System.out.println("暂停"); } try { lock.wait(); System.out.println("等待"); } catch(InterruptedException e) { } } if(!line.isRunning()&&!over) { System.out.println("开始播放"); line.start(); } if (over&&line.isRunning()) { System.out.println("停止播放"); jSliderPlayProgress.setValue(0); isNext=false; line.drain(); line.stop(); line.close(); } jSliderPlayProgress.setValue((int)line.getMicrosecondPosition()); line.write(data, 0, nBytesRead); } //根据播放模式选择下一首歌 nextmusic(); } } } catch(Exception e) { e.printStackTrace(); } finally { if(din != null) { try { din.close(); } catch(IOException e) { } } } } //设置播放器滚动条 public void setVolume() { if(line!=null) { if(line.isControlSupported(FloatControl.Type.MASTER_GAIN)) { jSliderVolume.setEnabled(true); volume= (FloatControl)line.getControl( FloatControl.Type.MASTER_GAIN ); jSliderVolume.setMinimum((int)volume.getMinimum()); jSliderVolume.setMaximum((int)volume.getMaximum()); //jSliderVolume.setValue((int)(volume.getMinimum()+(4*(volume.getMaximum()-volume.getMinimum()))/5)); volume.setValue((float)(volume.getMinimum()+(4*(volume.getMaximum()-volume.getMinimum()))/5)); } } else { volume=null; jSliderVolume.setEnabled(false); } } private void nextmusic() { String mode=Setting.getMode(); if (isNext&&!mode.equals("one")) {//单曲播放就不执行 int nextid=0;//将要播放的id int currentid=Integer.parseInt(this.music.getId()); System.out.println(mode); if (mode.equals("default")&&(currentid==MusicList.getList().size()-1)){ return; } if (mode.equals("rand")) { Random random = new Random(); nextid=Math.abs(random.nextInt())%MusicList.getList().size(); }else if (mode.equals("onecircle")) { nextid=currentid; }else if (mode.equals("default")&&!(currentid==MusicList.getList().size()-1)) { nextid=currentid+1; }else if (mode.equals("morecircle")) { nextid=(currentid==MusicList.getList().size()-1)?0:currentid+1; } JTable jTable=ViewList.getList().get(0).getJt(); if(nextid==0){//第一个 jTable.setRowSelectionInterval(0,0); }else { jTable.setRowSelectionInterval(nextid-1,nextid); } this.stopplay(); ThreadList.getList().clear(); p=new Player(jSliderVolume,jSliderPlayProgress); p.setMusic(MusicList.getList().get(nextid)); ThreadList.getList().add(p); p.start(); } } //开始 public void startplay(){ over=false; } //停止 public void stopplay(){ over=true; } // 暂停 public void userPressedPause() { paused = true; } //继续 public void userPressedPlay() { synchronized(lock) { paused = false; lock.notifyAll(); } } public void Pause(){ if (paused) { synchronized(lock) { paused = false; lock.notifyAll(); } }else{ paused = true; } } }
这个主要是播放音乐的类,播放,暂停,停止,上一首,下一首都有了
View.java
package com.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; 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.JPanel; import javax.swing.JRootPane; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.ScrollPaneConstants; import javax.swing.SwingConstants; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.TableCellRenderer; import com.list.MusicList; import com.list.ThreadList; import com.list.ViewList; import com.model.Model; import com.model.Music; import com.service.Player; import com.service.Setting; import com.util.DirInput; import com.util.FileInput; import com.util.FileList; import com.util.List_File; public class View extends JFrame implements MouseListener,ActionListener,WindowListener { private JButton stop, open,del,next,pre; private Player p; private JPanel[] jPanels; private MusicList list; //private Long clickTime=0l; private JScrollPane jsp; private JTable jt; private JRootPane j; private Model model; private JSlider jSliderVolume; private JSlider jSliderPlayProgress; private FileInput fileinput; private DirInput dirInput; private JMenuBar jb; private JMenu jm; private JMenuItem fm,dm; private JComboBox jBox; public View(){ System.out.println(ViewList.getList().size()); if (ViewList.getList().size()==0) { Open(); } } private void Open() { //this.getRootPane().setWindowDecorationStyle(JRootPane.NONE); //this.setUndecorated(true); //菜单选项 jb=new JMenuBar(); jm=new JMenu("打开"); fm=new JMenuItem("文件"); dm=new JMenuItem("文件夹"); fm.addActionListener(this); dm.addActionListener(this); jb.add(jm); jm.add(fm); jm.add(dm); //this.setJMenuBar(jb); JPanel p1=new JPanel(); JPanel p2=new JPanel(); JPanel p3=new JPanel(); //增加菜单选项 j=new JRootPane(); j.setJMenuBar(jb); p2.add(j); open=new JButton("播放"); stop=new JButton("停止"); open.addMouseListener(this); stop.addMouseListener(this); pre=new JButton("上一首"); next=new JButton("下一首"); pre.addMouseListener(this); next.addMouseListener(this); p1.setLayout(new GridLayout(2,1)); JPanel jPanel2=new JPanel(); jPanel2.add(open); jPanel2.add(stop); jPanel2.add(pre); jPanel2.add(next); p1.add(jPanel2); /*p1.add(open); p1.add(stop); p1.add(pre); p1.add(next);*/ del=new JButton("删除"); del.addMouseListener(this); jSliderPlayProgress = new JSlider(); //播放进度条 jSliderPlayProgress.setValue(0); jSliderPlayProgress.setEnabled(false); jSliderPlayProgress.setPreferredSize(new Dimension(200, 20)); p1.add(jSliderPlayProgress); jSliderVolume = new JSlider(); //音量进度条 jSliderVolume.setValue(0); //jSliderPlayProgress.setEnabled(false); jSliderVolume.setPreferredSize(new Dimension(100, 20));//设置滚动条长度 jSliderVolume.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent evt) { System.out.println(jSliderVolume.getValue()); if (ThreadList.getList().size()!=0) { ThreadList.getList().get(0).getVolume().setValue((float)jSliderVolume.getValue()); } } }); String[] v={"顺序播放","随机播放","单曲循环","列表循环","单曲播放"}; jBox=new JComboBox(v); jBox.addActionListener(this); p2.add(jBox); p2.add(del); p2.add(jSliderVolume); jPanels=new JPanel[list.getList().size()]; for (int i = 0; i < list.getList().size(); i++) { Music music=list.getList().get(i); JPanel jPanel=new MyJPanel(music); JLabel jLabel=new JLabel(music.getName(),SwingConstants.CENTER); jLabel.setSize(300, 10); jLabel.setHorizontalTextPosition(JLabel.CENTER); jPanel.setBackground(Color.WHITE); jPanels[i]=jPanel; jPanel.addMouseListener(this); jPanel.add(jLabel); p3.add(jPanel); } p3.setBackground(Color.WHITE); p3.setLayout(new GridLayout(10, 1)); p3.setSize(320, 500); this.add(p1,BorderLayout.NORTH); this.add(p2,BorderLayout.SOUTH); model=new Model(); //添加表 jt=new JTable(model){ // 设置jtable的单元格为透明的 public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); if (c instanceof JComponent) { ((JComponent) c).setOpaque(false); } return c; } };; jt.setOpaque(false); jt.setRowHeight(30); jt.setSelectionMode(ListSelectionModel.SINGLE_SELECTION ); jt.setShowHorizontalLines(false); jt.setSelectionBackground(new Color(189,215,238)); jt.addMouseListener(this); jsp = new JScrollPane(jt); jsp.setOpaque(false); jsp.getViewport().setOpaque(false); //addmusic(); //this.add(p3,BorderLayout.CENTER); this.add(jsp,BorderLayout.CENTER); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.addWindowListener(this); Image image=this.getToolkit().getImage("img/icon.jpg"); this.setIconImage(image); this.setTitle("音乐播放器"); ImageIcon icon = new ImageIcon("img/bg.jpg"); JLabel lab = new JLabel(icon); // 将图片放入到label中 lab.setBounds(0, 0, icon.getIconWidth(), icon.getIconHeight()); // 设置放有图片的label的位置 this.getContentPane().add(lab, -1); // jthis本身是窗体,不能放置任何组件,用getContentPane()方法得到this的默认内容面板,将lab放入其中,-1表示放入面板的下层 this.getContentPane().add(jsp, 0); // 0表示放在面板的最顶层 Container con = this.getContentPane(); ((JPanel)con).setOpaque(false); // 设置面板为透明的 p2.setOpaque(false); jSliderVolume.setOpaque(false); jPanel2.setOpaque(false); p1.setOpaque(false); p3.setOpaque(false); jSliderPlayProgress.setOpaque(false); this.setLocation(400, 200); this.setSize(337, 525); this.setResizable(false); this.setVisible(true); } @Override public void mouseClicked(MouseEvent e) { System.out.println("开始播放"); if (e.getSource()==open) { if (p==null) {//开始 p=new Player(jSliderVolume,jSliderPlayProgress); p.setMusic(MusicList.getList().get(0)); jt.setRowSelectionInterval(0,0); ThreadList.add(p); open.setText("暂停"); p.start(); }else{//继续 if (ThreadList.getList().size()!=0) { p=ThreadList.getList().get(0); } String s=p.isPaused()?"暂停":"播放"; open.setText(s); p.Pause(); } }else if (e.getSource()==stop) { if (ThreadList.getList().size()!=0) { p=ThreadList.getList().get(0); } if (p!=null) { p.stopplay(); p=null; open.setText("播放"); } }else if (e.getSource()==pre) {//上一首 premusic(); }else if (e.getSource()==next) {//下一首 nextmusic(); }else if (e.getSource()==del) { delmusic(); }else if (e.getSource()==jt&&e.getClickCount()==2) {//双击 clickmusic(); } } private void clickmusic() { //双击Jtable System.out.println("点击了"); int rowNum = this.jt.getSelectedRow(); System.out.println(rowNum); if(rowNum == -1) { JOptionPane.showMessageDialog(this, "你没有选择一项"); return; } ArrayListlist=ThreadList.getList(); System.out.println(list.size()+"音乐文件数目"); if (list.size()==0) { p=new Player(jSliderVolume,jSliderPlayProgress); p.setMusic(MusicList.getList().get(rowNum)); ThreadList.add(p); open.setText("暂停"); p.start(); }else{ System.out.println("停止"); list.get(0).stopplay(); list.clear(); p=new Player(jSliderVolume,jSliderPlayProgress); p.setMusic(MusicList.getList().get(rowNum)); open.setText("暂停"); list.add(p); p.start(); } } private void delmusic() { int rowNum = this.jt.getSelectedRow(); MusicList.getList().remove(rowNum); System.out.println(MusicList.getList().size()); jt.setModel(new Model()); ArrayList list=ThreadList.getList(); p=new Player(jSliderVolume,jSliderPlayProgress); System.out.println(list.size()+"大小"); if (list.size()!=0) { list.get(0).stopplay(); list.clear(); open.setText("暂停"); if(rowNum==0){//第一个 System.out.println("第一个"); jt.setRowSelectionInterval(0,0); p.setMusic(MusicList.getList().get(rowNum)); }else if(rowNum==MusicList.getList().size()){//最后一个 System.out.println("最后一个"); jt.setRowSelectionInterval(rowNum-2,rowNum-1); p.setMusic(MusicList.getList().get(rowNum-1)); }else { System.out.println("中间"); jt.setRowSelectionInterval(rowNum-1,rowNum); p.setMusic(MusicList.getList().get(rowNum)); } list.add(p); p.start(); } } public JTable getJt() { return jt; } private void premusic() { System.out.println("上一首"); ArrayList list=ThreadList.getList(); int id=Integer.parseInt(list.get(0).getMusic().getId()); if(id!=0){ if (id==1) { jt.setRowSelectionInterval(0,0); }else{ jt.setRowSelectionInterval(id-2,id-1); } System.out.println(id); list.get(0).stopplay(); list.clear(); p=new Player(jSliderVolume,jSliderPlayProgress); p.setMusic(MusicList.getList().get(id-1)); System.out.println(id-1); open.setText("暂停"); list.add(p); p.start(); } } private void nextmusic() { System.out.println("下一首"); ArrayList list=ThreadList.getList(); int id=Integer.parseInt(list.get(0).getMusic().getId()); System.out.println(id); if(id!=MusicList.getList().size()-1){ //122 jt.setRowSelectionInterval(id,id+1); //123条 list.get(0).stopplay(); list.clear(); p=new Player(jSliderVolume,jSliderPlayProgress); p.setMusic(MusicList.getList().get(id+1)); System.out.println(id+1); open.setText("暂停"); list.add(p); p.start(); } } //判断双击 /* private boolean checkClickTime() { long nowTime = (new Date()).getTime(); if ((nowTime - clickTime) < 300) { clickTime = nowTime; return true; } clickTime = nowTime; return false; }*/ private void addmusic(String path) {//增加mp3文件夹 System.out.println("增加mp3文件夹"); ArrayList musiclist=MusicList.getList(); List_File fm = new List_File(); ArrayList FileList = fm.serachFiles(path); for (int i = 0; i < FileList.size(); i++) { Music music= new Music(); music.setId(musiclist.size()+""); String[] s=(String[]) FileList.get(i); music.setName(s[0]); music.setPath(s[1]); musiclist.add(music); } jt.setModel(new Model()); } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void actionPerformed(ActionEvent e) { if (e.getSource()==fm) {//添加mp3文件 if(fileinput==null) fileinput = new FileInput(this); fileinput.open(); File[] s=fileinput.getFiles(); ArrayList musiclist=MusicList.getList(); if(s!=null){ for(int i=0;i list=MusicList.getList(); for (int i = 0; i < list.size(); i++) { FileList.writeFile("file/musiclist.txt",list.get(i).getId()+","+list.get(i).getName()+"," +list.get(i).getPath()+"\n"); } } } @Override public void windowDeactivated(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub System.out.println("open"); File file=new File("file/musiclist.txt"); if (file.exists()==false) { try { file.createNewFile(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } }else { FileList.readFileByLines("file/musiclist.txt"); jt.setModel(new Model()); } } }
剩下的代码在后面附件上有,现在主要是有几个小问题,第一,我还没有找到获取音乐文件具体信息比较好的办法,所以每一首暂时还没有歌手,作曲的信息,第二界面有点难看,见谅了,第三个是打包成jar文件会有路径问题,暂时还没办法解决,我是直接在myeclipse上运行,一切正常,就是打包有点小问题
暂时先说这些了,这个是我业余时间的项目,有什么不足的,大家都可以提出来。
下载地址:音乐播放器
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。
网站栏目:java音乐播放器实现代码
转载来源:http://myzitong.com/article/ihcijo.html