Java默认支持的音频格式有AU,AIFF,WAV,MIDI,RFM,并没有最常见的mp3,貌似因为mp3这种压缩格式是需要版权的。
/**
* 读取一个音频文件
*/
private JButton getOpenFile()
{
if(btnOpenFile == null)
{
btnOpenFile = new JButton("选择文件");
//添加按钮事件监听器
btnOpenFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//创建文件选择器对象
JFileChooser fileChooser = new JFileChooser();
//设置文件过滤
fileChooser.setFileFilter(new FileNameExtensionFilter("支持音频文件类型 (*.mp3,*.wav,*.mid)","mp3","wav","mid"));
//显示文件选择对话框
fileChooser.showOpenDialog(MusicPlay.this);
//获取选择的文件对象
selectFile = fileChooser.getSelectedFile();
//在文本框中显示文件信息
if(selectFile != null)
filePath.setText(selectFile.getAbsolutePath());
}
});
}
return btnOpenFile;
}
/**
* 用Applet的AudioClip类的audioClip播放音频
*/
public JButton getPlayButton()
{
if(btnPlay == null)
{
btnPlay = new JButton("播放");
btnPlay.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println(btnPlay.getText());
if("播放"==(btnPlay.getText()))
{
if(selectFile != null)
{
try
{
if(audioClip != null)
audioClip.stop();
//获取音频剪辑对象
audioClip = Applet.newAudioClip(selectFile.toURI().toURL());
audioClip.play();
btnPlay.setText("暂停");
}
catch(MalformedURLException e1)
{
e1.printStackTrace();
}
}
}
else if("暂停"==(btnPlay.getText()))
{
audioClip.stop();
btnPlay.setText("播放");
}
}
});
}
return btnPlay;
}