elipse给我一个音乐播放器的例程
时间: 2023-06-11 10:09:00 浏览: 56
以下是一个简单的音乐播放器的例程,使用Java语言和Swing GUI库编写:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
public class MusicPlayer extends JFrame implements ActionListener {
private JButton playButton, pauseButton, stopButton;
private JLabel nowPlayingLabel;
private JFileChooser fileChooser;
private File currentFile;
private MusicPlayerThread playerThread;
public MusicPlayer() {
super("Music Player");
// Create GUI components
playButton = new JButton("Play");
playButton.addActionListener(this);
pauseButton = new JButton("Pause");
pauseButton.addActionListener(this);
stopButton = new JButton("Stop");
stopButton.addActionListener(this);
nowPlayingLabel = new JLabel("No file selected");
fileChooser = new JFileChooser();
// Add components to frame
JPanel buttonPanel = new JPanel();
buttonPanel.add(playButton);
buttonPanel.add(pauseButton);
buttonPanel.add(stopButton);
add(buttonPanel, BorderLayout.NORTH);
add(nowPlayingLabel, BorderLayout.CENTER);
// Set frame properties
setSize(400, 100);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == playButton) {
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
currentFile = fileChooser.getSelectedFile();
nowPlayingLabel.setText("Now playing: " + currentFile.getName());
if (playerThread != null) {
playerThread.stopPlaying();
}
playerThread = new MusicPlayerThread(currentFile);
playerThread.start();
}
} else if (e.getSource() == pauseButton) {
if (playerThread != null) {
playerThread.pausePlaying();
}
} else if (e.getSource() == stopButton) {
if (playerThread != null) {
playerThread.stopPlaying();
nowPlayingLabel.setText("No file selected");
}
}
}
private class MusicPlayerThread extends Thread {
private File musicFile;
private boolean playing, paused;
public MusicPlayerThread(File file) {
musicFile = file;
}
public void run() {
try {
playing = true;
paused = false;
AudioInputStream audioStream = AudioSystem.getAudioInputStream(musicFile);
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
clip.start();
while (playing) {
if (paused) {
Thread.sleep(100);
}
if (!clip.isActive()) {
playing = false;
}
}
clip.close();
audioStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopPlaying() {
playing = false;
}
public void pausePlaying() {
paused = true;
}
}
public static void main(String[] args) {
MusicPlayer player = new MusicPlayer();
player.setVisible(true);
}
}
```
该音乐播放器包含三个按钮:播放、暂停和停止,以及显示当前正在播放的文件名称的标签。单击“播放”按钮后,会弹出文件选择对话框,并选择要播放的音乐文件。播放器使用Java的AudioSystem和Clip类播放音乐。在播放音乐时,可以单击“暂停”按钮暂停播放,并单击“停止”按钮停止播放。