java编的音乐播放器,只能播放部分MP3文件

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;
this.name = 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 = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, audioFormat.getSampleRate(), 16, audioFormat.getChannels(), audioFormat.getChannels()*2, audioFormat.getSampleRate(), audioFormat.isBigEndian());
audioInputStream = AudioSystem.getAudioInputStream(audioFormat, audioInputStream);

}

        //打开输出设备
        DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat,AudioSystem.NOT_SPECIFIED);
        sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
        sourceDataLine.open(audioFormat);
        sourceDataLine.start();
        //启动播放线程
        new Thread() {
            @Override
            public 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();
            }
}

}

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
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.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;

import com.zy.play.Player;

public class MusicPanel extends JFrame{

private JButton add, playbtn, stopbtn, deletebtn, deleteAllbtn, upbtn, downbtn;//播放、停止、删除、删除全部、向上。向下按钮
private JTable table; //歌曲信息表
private Player player;
private JPanel jpl1,jpl2;
public MusicPanel() {
    initCompont();
}
/**
 * 初始化界面
 */
private void initCompont() {
    //各个按钮赋初始值
    add = new JButton("导入");
    playbtn = new JButton("试听");
    stopbtn = new JButton("停止");
    deletebtn = new JButton("单曲删除");
    deleteAllbtn = new JButton("全部删除");
    upbtn = new JButton("上一首");
    downbtn = new JButton("下一首");

    //导入按钮点击设置
    add.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            addFile();  
        }   
    });

    //试听按钮点击设置
    playbtn.addActionListener(new ActionListener() {

        @Override
        public 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() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if(player != null) {
                player.stop();
                player = null;
            }
        }
    });

    //单曲删除按钮点击设置
    deletebtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int rowNum = table.getSelectedRow();
            if(rowNum != -1) {
                ((DefaultTableModel)table.getModel()).removeRow(rowNum);
            }
        }   
    });

    //删除全部按钮点击设置
    deleteAllbtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            for(int i = table.getRowCount()-1; i>=0; i--) {
                ((DefaultTableModel)table.getModel()).removeRow(i);
            }
        }
    });

    downbtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int n = table.getSelectedRow() + 1;
            if(n < table.getRowCount()) {
                table.setRowSelectionInterval(n, n);
            }
        }
    });

    upbtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int n = table.getSelectedRow() - 1;
            if(n < -1) {
                n = table.getRowCount() - 1;
            }
            if(n >= 0) {
                table.setRowSelectionInterval(n, n);
            }
        }

    });



    //添加各个按钮
    jpl1= new JPanel(new GridLayout(1,7));
    jpl1.add(add);
    jpl1.add(playbtn);
    jpl1.add(stopbtn);
    jpl1.add(deletebtn);
    jpl1.add(deleteAllbtn);
    jpl1.add(upbtn);
    jpl1.add(downbtn);
    //this.setLayout(new BorderLayout());
    this.add(jpl1,"North");

    Vector<String> tableContent = new Vector<String>(); //表格内容
    Vector<String> columnName = new Vector<String>();//歌曲信息表格列名称
    columnName.add("歌曲名称");
    columnName.add("存放路径");

    //设置table
    table = new JTable(tableContent, columnName);
    table.setSelectionBackground(Color.blue);
    table.setSelectionForeground(Color.LIGHT_GRAY);
    jpl2=new JPanel();

    jpl2.add(new JScrollPane(table), BorderLayout.CENTER);
    this.add(jpl2,"Center");
    this.setSize(650, 210);
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

/**
 * 添加文件
 */
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, "打开");
    //获取文件并添加到table
    if(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);
}

public static void main(String[] args) {
    MusicPanel test=new MusicPanel();
}

}


报错:java.io.IOException: Resetting to invalid mark

2个回答

想要播放更多格式,请参考JJMPEG。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问