我正在尝试制作一个简单的基于 java 框架的音乐播放器。我已经成功这样做了,但如果它只播放 .wav 文件。即使我将加载文件条件更改为 .mp3 然后加载 mp3 文件,它也会显示 UnsupportedAudioFileException .. 请帮我纠正它。这是我的代码,请告诉我需要进行更正以停止在 cmd 中显示此错误。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.sound.sampled.*;
import java.io.*;
import java.net.*;
public class MusicPlayer extends Thread implements ActionListener {
JLabel label;
AudioInputStream ai;
Clip c;
JComboBox playlist;
JButton play, loop, stop, open;
JFrame f;
String dest, str;
JTextField tf;
URL u;
File file;
MusicPlayer() {
f = new JFrame("Music Player");
f.setLayout(null);
f.setSize(620, 300);
f.setVisible(true);
tf = new JTextField();
tf.setBounds(25, 50, 565, 40);
tf.setFont(new Font("Monotype Corsiva", Font.BOLD, 20));
f.add(tf);
tf.setHorizontalAlignment(JTextField.RIGHT);
play = new JButton("play");
play.setBounds(100, 150, 120, 30);
play.addActionListener(this);
f.add(play);
loop = new JButton("loop");
loop.setBounds(300, 150, 120, 30);
loop.addActionListener(this);
f.add(loop);
stop = new JButton("stop");
stop.setBounds(450, 150, 120, 30);
stop.addActionListener(this);
f.add(stop);
open = new JButton("open");
open.setBounds(100, 200, 420, 30);
open.addActionListener(this);
f.add(open);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae) {
String dest;
if (ae.getActionCommand().equals("open")) {
FileDialog fd = new FileDialog(f, "Open Box", FileDialog.LOAD);
fd.setSize(300, 300);
fd.setVisible(true);
String s1 = "wav";
String sng = fd.getFile();
dest = fd.getDirectory() + fd.getFile();
if (sng.toLowerCase().endsWith(s1)) {
tf.setText(sng);
file = new File(dest);
} else {
JOptionPane.showMessageDialog(f, "Select a valid file format");
}
try {
c = AudioSystem.getClip();
file = new File(dest);
ai = AudioSystem.getAudioInputStream(file);
} catch (Exception e) {
e.printStackTrace();
}
}
if (ae.getActionCommand().equals("play")) {
try {
ai = AudioSystem.getAudioInputStream(file);
c.close();
c = AudioSystem.getClip();
c.open(ai);
c.start();
} catch (Exception e) {
e.printStackTrace();
}
}
if (ae.getActionCommand().equals("loop")) {
try {
ai = AudioSystem.getAudioInputStream(file);
c.close();
c = AudioSystem.getClip();
c.open(ai);
c.loop(Clip.LOOP_CONTINUOUSLY);
} catch (Exception e) {
e.printStackTrace();
}
}
if (ae.getActionCommand().equals("stop")) {
c.stop();
c.close();
}
}
public static void main(String args[]) {
new MusicPlayer();
}
}