Поэтому я пытаюсь создать аудиоплеер только потому, что хочу лучше понять стеки и графические интерфейсы Java. Я ожидал, что при выборе аудиофайла он должен был воспроизводиться, что он и делал раньше, но сейчас этого не происходит. Я вернулся к предыдущему коду, чтобы увидеть разницу, но я не увидел ничего такого, что могло бы помешать его работе, у меня также не было никаких ошибок в терминале.
Я пробовал просмотреть документацию Java se 8 и несколько видеороликов на YouTube об аудиоклипах в Java, и все казалось правильным, и я уже не знал, в чем проблема, также я удалил current = NumberofClips; из кода в качестве теста, и по какой-то причине действительно воспроизводился только один из двух аудиофайлов.
вот воспроизводимая версия кода:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.io.File;
import java.util.Stack;
import javax.imageio.ImageIO;
import javax.sound.sampled.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public class MusicPlayerGui extends JFrame implements ActionListener {
JMenu songMenu;
JMenuItem loadMusic;
JMenuItem loadPlaylist;
// Button
JPanel playbackBtns;
JButton prevButton;
JButton playButton;
JButton pauseButton;
JButton nextButton;
// Music stuff
Stack clips = new Stack();
int next;
int prev;
int current = 0;
float frameRate;
int numberofClips;
boolean play = true;
boolean first = true;
boolean playlist;
public MusicPlayerGui() {
super("Music Player");
setSize(400, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setLayout(null);
getContentPane().setBackground(BG_Color);
// Ignore this
addUiComponents();
}
private void addUiComponents() {
addToolbar();
addPlaybackBtns();
// removed the rest of the function
}
private void addToolbar() {
toolbar = new JToolBar();
toolbar.setBounds(0, 0, getWidth(), 30);
toolbar.setFloatable(false);
add(toolbar);
menuBar = new JMenuBar();
toolbar.add(menuBar);
songMenu = new JMenu("Song");
menuBar.add(songMenu);
loadMusic = new JMenuItem("Load music from directory");
loadMusic.addActionListener(this);
songMenu.add(loadMusic);
loadPlaylist = new JMenuItem("Load playlist from directory");
loadPlaylist.addActionListener(this);
songMenu.add(loadPlaylist);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == loadMusic) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("Music Files", "wav"));
int response = fileChooser.showOpenDialog(null);
if (response == JFileChooser.APPROVE_OPTION) {
File file = new File(fileChooser.getSelectedFile().getAbsolutePath());
try (AudioInputStream aS = AudioSystem.getAudioInputStream(file)) {
if (play == true) {
enablePlayButton();
clips.get(current).stop();
}
numberofClips++;
Clip clip = AudioSystem.getClip();
current = numberofClips;
clip.open(aS);
clips.push(clip);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
System.out.println(ex);
}
}
}
if (e.getSource() == loadPlaylist) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int response = fileChooser.showOpenDialog(null);
if (response == JFileChooser.APPROVE_OPTION) {
File files = new File(fileChooser.getSelectedFile().getAbsolutePath());
for (File file : files.listFiles()) {
try (AudioInputStream aS = AudioSystem.getAudioInputStream(file)) {
if (play == true) {
enablePlayButton();
clips.get(current).stop();
}
numberofClips++;
Clip clip = AudioSystem.getClip();
playlist = true;
clip.open(aS);
clips.push(clip);
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException ex) {
System.out.println(ex);
}
}
}
}
if (e.getSource() == playButton) {
enablePauseButton();
clips.get(current).start();
next = current + 1;
prev = current - 1;
if (playlist) {
if ((clips.empty() && clips.get(current).isRunning() != false) && next > numberofClips) {
enablePauseButton();
clips.get(next).start();
current = next;
}
}
}
if (e.getSource() == pauseButton) {
enablePlayButton();
clips.get(current).stop();
}
if (e.getSource() == prevButton) {
if (first != true && prev < 0) {
enablePlayButton();
clips.get(current).stop();
clips.get(prev).start();
current = prev;
next = current + 1;
prev = current - 1;
}
}
}
}
Также вот основной файл, который можно запустить:
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MusicPlayerGui().setVisible(true);;
}
});
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... em-working