日期:2014-05-20  浏览次数:20786 次

旧帖重发,解决许多人关心的Java应用程序播放音乐的问题,高手们过来看看吧
[code=Java][/code]
import java.awt.*;
import java.awt.event.*;
import sun.audio.*; 
import java.io.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.event.*;
public class PlayMusic extends JFrame implements ActionListener,ListSelectionListener{

static JButton play=new JButton("播放");
  static JButton stop=new JButton("停止");
static JButton loop=new JButton("循环播放");
static DefaultListModel data=new DefaultListModel();
static JList list=new JList(data);
static AudioStream as;
static String[] musicName={"1.wav","2.wav","3.wav","4.wav"};
public static void main(String[] args) throws IOException{
PlayMusic s=new PlayMusic();
for(int i=0;i<musicName.length;i++){
data.addElement(musicName[i]);
}

list.setSelectedIndex(0);//设置选的是第一个
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane jscrolling=new JScrollPane(list);
JPanel north=new JPanel(new FlowLayout());
north.add(play);
north.add(stop);
north.add(loop);
JPanel center=new JPanel(new GridLayout(1,1));
center.add(jscrolling);
JPanel all=new JPanel(new BorderLayout());
all.add("North",north);
all.add("Center",center);
s.add(all);
play.addActionListener(s);
stop.addActionListener(s);

list.addListSelectionListener(s);
s.setSize(300,400);
s.validate();
s.pack();
s.setVisible(true);
}
public void actionPerformed(ActionEvent arg0) {
Object e=arg0.getSource();
if(e==play)
AudioPlayer.player.start(as); 
else if(e==stop)
AudioPlayer.player.stop(as); 
}

public void valueChanged(ListSelectionEvent arg0){

if(!arg0.getValueIsAdjusting())
try {
InputStream out= new FileInputStream(list.getSelectedValues().toString());
as=new AudioStream(out);
} catch (FileNotFoundException e) {
System.out.println("找不到文件!");

} catch (IOException e) {
System.out.println("还是找不到!");

}


}
}

运行时出现的异常,找不到文件,但是我把文件已经放在了相关项目的文件目录下,麻烦各位高手详述错误原因,已经试了很多次了,还是找不出解决方法。

------解决方案--------------------
list.getSelectedValues()返回选择元素的数组,toString()返回对象的引用地址,而不是文件地址。

改为InputStream out= new FileInputStream(musicName[list.getSelectedIndex()]);
------解决方案--------------------
学习