引起我注意的另一种实现答案的方法;使用AudioSystem.getAudioFileTypes()返回指定文件夹中所有支持的音频文件。我是一个相当缺乏经验的编码员,我无法将这种方法整合到我给出的答案中
File someFolder = new File("pathname");
Object[] wavFiles = someFolder.listFiles(wavExtensionFilenameFilter);
JComboBox songComboBox = new JComboBox(wavFiles);
有人能告诉我这是怎么做到的吗?
答案 0 :(得分:4)
以下源代码将显示特定于Java Sound所理解的文件类型的JFileChooser
。一旦用户选择任何声音片段,该应用程序。将获得该目录中所有剪辑的列表,并将其显示在组合中。
在从组合中选择剪辑时,我们可以play the sound in a javax.sound.sample.Clip
(或使用Java Sound API的其他方式),但我们选择。使用Desktop
打开文件的1.6+'one-liner'(在系统默认播放器中)。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.sound.sampled.*;
import java.io.*;
class GetSoundsByFileType {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
AudioFileFormat.Type[] formatTypes = AudioSystem.getAudioFileTypes();
String[] types = new String[formatTypes.length];
for(int ii=0; ii<types.length; ii++) {
types[ii] = formatTypes[ii].getExtension();
}
FileTypesFilter fileTypesFilter = new FileTypesFilter(types);
// Just to confuse things, JFileChooser accepts a
// different type of filter!
FileNameExtensionFilter extensionFilter =
new FileNameExtensionFilter("Sound clips", types);
JFileChooser fc = new JFileChooser();
fc.setAcceptAllFileFilterUsed(false);
fc.addChoosableFileFilter(extensionFilter);
int result = fc.showOpenDialog(null);
if (result==JFileChooser.APPROVE_OPTION) {
File startAt = fc.getSelectedFile();
startAt = startAt.getParentFile();
File[] files = startAt.listFiles(fileTypesFilter);
final JComboBox clipCombo = new JComboBox(files);
clipCombo.addActionListener( new ActionListener(){
// 1.6+
Desktop desktop = Desktop.getDesktop();
public void actionPerformed(ActionEvent ae) {
try {
desktop.open( (File)clipCombo.getSelectedItem() );
} catch(Exception e) {
e.printStackTrace();
}
}
} );
JOptionPane.showMessageDialog(null, clipCombo);
}
}
});
}
}
class FileTypesFilter implements FilenameFilter {
private String[] types;
FileTypesFilter(String[] types ) {
this.types = types;
}
public boolean accept(File dir, String name) {
for (String type:types) {
if (name.toLowerCase().endsWith(type.toLowerCase())) {
return true;
}
}
return false;
}
}