当前位置:文档之家› 音乐播放器java源代码

音乐播放器java源代码

package com.ding.player;import java.io.File;import java.io.IOException;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;public class Player {private String path;//文件路径private String name;//文件名称private AudioFormat audioFormat;//播放格式private AudioInputStream audioInputStream;//音乐播放输入流private SourceDataLine sourceDataLine;// 播放设备private boolean isStop = false;// 播放停止标志/*** 创建对象时需要传入播放路径及文件名称* @param path* @param name*/public Player(String path ,String name) {this.path = path; = name;}/*** 播放音乐*/public void play() {File file = new File(path + name);try {//获取音乐播放流audioInputStream = AudioSystem.getAudioInputStream(file);//获取播放格式audioFormat = audioInputStream.getFormat();/*System.out.println("取样率:"+ audioFormat.getSampleRate());Map map = audioFormat.properties();Iterator it = map.entrySet().iterator();while(it.hasNext()) {Map.Entry m = (Entry) it.next();System.out.println(m.getKey()+":"+m.getValue());}*///其它格式音乐文件处理if(audioFormat.getEncoding() !=AudioFormat.Encoding.PCM_SIGNED) {audioFormat = newAudioFormat(AudioFormat.Encoding.PCM_SIGNED, audioFormat.getSampleRate(), 16, audioFormat.getChannels(), audioFormat.getChannels()*2,audioFormat.getSampleRate(), audioFormat.isBigEndian());audioInputStream =AudioSystem.getAudioInputStream(audioFormat, audioInputStream);}//打开输出设备 dataLineInfo = new(SourceDataLine.class,audioFormat,AudioSystem.NOT_SPECIFIED);sourceDataLine = (SourceDataLine)AudioSystem.getLine(dataLineInfo);sourceDataLine.open(audioFormat);sourceDataLine.start();//启动播放线程new Thread() {@Overridepublic void run() {try {int n = 0;byte tempBuffer[] = new byte[320];while(n != -1) {//停止播放入口,如果isStop被置为真,结束播放if(isStop) break;//将音乐输入流的数据读入tempBuffer缓存n = audioInputStream.read(tempBuffer,0 , tempBuffer.length);if(n>0) {//将缓存数据写入播放设备,开始播放sourceDataLine.write(tempBuffer, 0, n);}}audioInputStream.close();sourceDataLine.drain();sourceDataLine.close();} catch (IOException e) {e.printStackTrace();throw new RuntimeException();}}}.start();} catch (Exception e) {e.printStackTrace();System.exit(0);throw new RuntimeException();}}/*** 停止播放*/public void stop() {try {isStop = true;audioInputStream.close();sourceDataLine.drain();sourceDataLine.close();} catch (IOException e) {e.printStackTrace();}}}package com.ding.UI;import java.awt.BorderLayout;import java.awt.Color;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.File;import java.util.Vector;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFileChooser;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTable;import javax.swing.filechooser.FileNameExtensionFilter;import javax.swing.table.DefaultTableModel;import com.ding.player.Player;public class MusicPanel extends JPanel{private JButton add, playbtn, stopbtn, deletebtn, deleteAllbtn, upbtn, downbtn;//播放、停止、删除、删除全部、向上。

向下按钮private JTable table; //歌曲信息表private Player player;public MusicPanel() {initCompont();}/*** 初始化界面*/private void initCompont() {//各个按钮赋初始值add = new JButton("导入");playbtn = new JButton("试听");stopbtn = new JButton("停止");deletebtn = new JButton("单曲删除");deleteAllbtn = new JButton("全部删除");upbtn = new JButton(new ImageIcon("img/up.png"));downbtn = new JButton(new ImageIcon("img/down.png"));//导入按钮点击设置add.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {addFile();}});//试听按钮点击设置playbtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {if(player!=null) {player.stop();player = null;}int rowNum = table.getSelectedRow();if(rowNum != -1) {player = new Player((String)table.getValueAt(rowNum, 1) + "\\" ,(String)table.getValueAt(rowNum, 0));System.out.println((String)table.getValueAt(rowNum,1)+"\\"+(String)table.getValueAt(rowNum, 0));player.play();}}});//停止按钮点击设置stopbtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {if(player != null) {player.stop();player = null;}}});//单曲删除按钮点击设置deletebtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {int rowNum = table.getSelectedRow();if(rowNum != -1) {((DefaultTableModel)table.getModel()).removeRow(rowNum);}}});//删除全部按钮点击设置deleteAllbtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {for(int i = table.getRowCount()-1; i>=0; i--) {((DefaultTableModel)table.getModel()).removeRow(i);}}});downbtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {int n = table.getSelectedRow() + 1;if(n < table.getRowCount()) {table.setRowSelectionInterval(n, n);}}});upbtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {int n = table.getSelectedRow() - 1;if(n < -1) {n = table.getRowCount() - 1;}if(n >= 0) {table.setRowSelectionInterval(n, n);}}});//添加各个按钮JPanel btnPanel = new JPanel();btnPanel.add(add);btnPanel.add(playbtn);btnPanel.add(stopbtn);btnPanel.add(deletebtn);btnPanel.add(deleteAllbtn);btnPanel.add(upbtn);btnPanel.add(downbtn);this.setLayout(new BorderLayout());this.add(btnPanel, BorderLayout.NORTH);Vector<String> tableContent = new Vector<String>(); //表格内容Vector<String> columnName = new Vector<String>();//歌曲信息表格列名称columnName.add("歌曲名称");columnName.add("存放路径");//设置tabletable = new JTable(tableContent, columnName);table.setSelectionBackground(Color.blue);table.setSelectionForeground(Color.LIGHT_GRAY);this.add(new JScrollPane(table), BorderLayout.CENTER);this.setSize(300, 210);}/*** 添加文件*/private void addFile() {JFileChooser fc = new JFileChooser();//设置选入文件类型FileNameExtensionFilter filter = new FileNameExtensionFilter("mp3 or wav file", "mp3","wav","MP3","WAV");fc.setFileFilter(filter);fc.setFileSelectionMode(JFileChooser.FILES_ONLY);//设置只选择文件fc.setMultiSelectionEnabled(true);//设置选择多个文件int intRetVal = fc.showDialog(this, "打开");//获取文件并添加到tableif(intRetVal == JFileChooser.APPROVE_OPTION) {File[] file = fc.getSelectedFiles();String name;for(File var : file) {name = var.getName().toLowerCase();if( name.endsWith(".mp3")|| name.endsWith(".wav")) {this.addMusicItem(var.getName() ,var.getParentFile().getAbsolutePath());}}}}/*** table的行中添加音乐文件名称name,音乐文件路径path* @param name* @param path*/private void addMusicItem(String name, String path ) {Vector<String> rowData = new Vector<String>();rowData.add(name);rowData.add(path);//rowData.add(time);DefaultTableModel tabMod= (DefaultTableModel) table.getModel();tabMod.addRow(rowData);}}。

相关主题