一个更完整和功能更强大的音乐播放器的代码
时间: 2024-02-23 09:01:14 浏览: 126
一款强大的播放器源码
以下是一个更完整和功能更强大的 Java 音乐播放器的代码示例,它包含了播放、暂停、停止、快进/快退、播放列表等功能:
```
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
public class MusicPlayer {
private Clip clip;
private boolean playing = false;
private boolean paused = false;
private int currentFrame = 0;
private int frameRate = 0;
private List<String> playlist;
private DefaultListModel<String> playlistModel;
public MusicPlayer() {
playlist = new ArrayList<String>();
playlistModel = new DefaultListModel<String>();
}
public void play(String filePath) {
try {
if (clip != null && clip.isActive()) {
clip.stop();
}
clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File(filePath)));
clip.start();
playing = true;
paused = false;
currentFrame = clip.getFramePosition();
frameRate = (int)clip.getFormat().getFrameRate();
} catch (Exception e) {
e.printStackTrace();
}
}
public void pause() {
if (clip != null && clip.isActive()) {
clip.stop();
paused = true;
playing = false;
currentFrame = clip.getFramePosition();
}
}
public void resume() {
if (clip != null && paused) {
clip.setFramePosition(currentFrame);
clip.start();
playing = true;
paused = false;
}
}
public void stop() {
if (clip != null && clip.isActive()) {
clip.stop();
playing = false;
paused = false;
currentFrame = 0;
}
}
public void skip(int seconds) {
if (clip != null && clip.isActive()) {
currentFrame += seconds * frameRate;
clip.setFramePosition(currentFrame);
}
}
public void addToPlaylist(String filePath) {
if (!playlist.contains(filePath)) {
playlist.add(filePath);
playlistModel.addElement(filePath);
}
}
public void removeFromPlaylist(int index) {
if (index >= 0 && index < playlist.size()) {
playlist.remove(index);
playlistModel.remove(index);
}
}
public void clearPlaylist() {
playlist.clear();
playlistModel.clear();
}
public void playFromPlaylist(int index) {
if (index >= 0 && index < playlist.size()) {
play(playlist.get(index));
}
}
public JList<String> getPlaylist() {
JList<String> list = new JList<String>(playlistModel);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
return list;
}
public boolean isPlaying() {
return playing;
}
public boolean isPaused() {
return paused;
}
public static void main(String[] args) {
MusicPlayer player = new MusicPlayer();
player.addToPlaylist("path/to/music1.mp3");
player.addToPlaylist("path/to/music2.mp3");
player.addToPlaylist("path/to/music3.mp3");
player.playFromPlaylist(0);
}
}
```
在上述代码中,我们添加了一个 `playing` 和 `paused` 的状态变量,用于跟踪当前音乐的播放状态。我们还添加了 `currentFrame` 和 `frameRate` 变量,用于实现快进/快退的功能。`addToPlaylist()`、`removeFromPlaylist()`、`clearPlaylist()` 和 `playFromPlaylist()` 方法用于管理播放列表。
我们还添加了一个 `getPlaylist()` 方法,用于返回一个包含播放列表的 `JList` 对象,以便在 GUI 界面上显示播放列表。
请注意,如果你需要在 GUI 界面上实现播放器,你需要在这个基础上进行更多的修改和扩展。
阅读全文