您好,登錄后才能下訂單哦!
本文實例為大家分享了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; } ArrayList<Player> list=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<Player> 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<Player> 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<Player> 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<Music> musiclist=MusicList.getList(); List_File fm = new List_File(); ArrayList<String[]> 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<Music> musiclist=MusicList.getList(); if(s!=null){ for(int i=0;i<s.length;i++){ Music music= new Music(); music.setId(musiclist.size()+""); music.setName(s[i].getName()); music.setPath(s[i].getAbsolutePath()); musiclist.add(music); jt.setModel(new Model()); } } }else if (e.getSource()==dm) { if(dirInput==null) dirInput = new DirInput(this); dirInput.open(); File s=dirInput.getFile(); if(s!=null){ addmusic(s.getAbsolutePath()); } }else if (e.getSource()==jBox) { //順序播放 (默認)default 隨機rand 單曲循環 onecircle 列表循環 morecircle 單曲播放 one if (ThreadList.getList().size()!=0) { p=ThreadList.getList().get(0); }else { p=new Player(jSliderVolume,jSliderPlayProgress); ThreadList.getList().add(p); } String[] s={"default","rand","onecircle","morecircle","one"}; Setting.setMode(s[jBox.getSelectedIndex()]); } } @Override public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub System.out.println("關閉kk"); } @Override public void windowClosing(WindowEvent e) { // TODO Auto-generated method stub System.out.println("close"); if (MusicList.getList().size()!=0) { System.out.println("寫入文件"); //清空之前的內容 FileList.clear("file/musiclist.txt"); ArrayList<Music> 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上運行,一切正常,就是打包有點小問題
暫時先說這些了,這個是我業余時間的項目,有什么不足的,大家都可以提出來。
下載地址:音樂播放器
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。