xiaohuihui183 2015-04-12 05:49 采纳率: 0%
浏览 2462

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条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)