I'm starting to learn Java and I wanted to make a program that was capable of playing music, however when it is executed the play button does not fulfill its purpose, do you have any idea what I may be doing wrong? I don't know if it helps but I program with visual studio code and I get that the applets are obsolete, maybe it has something to do with it too? I tried to implement everything that came to my mind from events with the mouse and others but the button still did not work This is the code, import everything that I thought could solve the error xd
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.AbstractButton;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.MouseAdapter;
import javax.sound.sampled.*;
import java.awt.Frame;
public class Musica extends Frame implements ActionListener {
JFrame f= new JFrame("Reproductor");
JLabel Lab1;
JButton b;
public Musica() {
Lab1 = new JLabel(new ImageIcon("04_ejercicio_cuatro/Pikachu.png"));
Lab1.setBounds(200, -100, 800, 800);
b= new JButton("Play");
b.setBounds(100,100,150,100);
f.add(b);
f.add(Lab1);
f.setSize(1200, 800);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.addActionListener(this);
}
public class rep extends Applet {}
public void actionPerformed(ActionEvent e) {
AudioClip sound;
sound = java.applet.Applet.newAudioClip(getClass().getResource("06_ejercicio_seis/background.wav"));
sound.play();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Musica().setVisible(true);
} });
}
}
public class Reproductor {
public static void main(String[] args) {
Musica reproductor = new Musica();
reproductor.setVisible(true);
}
}
Quite apart from the fact that it is an API already in disuse such as Applet , I have been able to play audio taking into account a couple of things:
One is to be 100% sure that the path to the .wav file is correct.
Another is that it
play()
plays the content so briefly that you can't hear it all, so you have to keep that playback process alive ( asleep()
can help ).Below the possible solution:
With the above, if it still doesn't work, then it's very likely that your .wav file isn't a type that it
AudioClip
can play or that it needs some sort of codec not supported by the Applet API.Edit:
Indeed, trying with several .wav I had some that did not play, while others did without problems; to keep it in mind ;)