我注意到了另一种执行答案的方法。使用AudioSystem.getAudioFileTypes()返回指定文件夹中的所有受支持的音频文件。我是一个经验不足的编码人员,无法在给定的答案中集成此方法
File someFolder = new File("pathname"); Object[] wavFiles = someFolder.listFiles(wavExtensionFilenameFilter); JComboBox songComboBox = new JComboBox(wavFiles);
谁能告诉我该怎么做?
以下资源将显示JFileChooser特定于Java Sound可以理解的文件类型的。用户选择任何声音剪辑后,即可使用该应用程序。将获得该目录中所有剪辑的列表,并以组合方式显示它们。
JFileChooser
从组合中选择剪辑后,我们可以以某种方式javax.sound.sample.Clip(或使用Java SoundAPI的其他方式)播放声音,但我们选择了。用于Desktop打开文件的1.6+“单行代码” (在系统默认播放器中)。
javax.sound.sample.Clip
Desktop
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; } }