I am unable to play a sound file after selecting from JComboBox and pressing the button. This programs purpose is to do exactly that. However, after I press the button, nothing plays and there are no errors being reported. My main problem is with these classes.
SMPanel.java
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
public class SMPanel
{
private JPanel mainPanel;
private JButton selectionButton;
SMListenerClass listener = new SMListenerClass(this);
public JComboBox comboBox;
static Object soundSelect;
public SMPanel()
{
mainPanel = new JPanel();
mainPanel.setLayout(new GridLayout(2, 2));
JComboBox comboBox = new JComboBox();
comboBox.addItem("1");
comboBox.addItem("2");
comboBox.addItem("3");
comboBox.setEditable(false);
soundSelect = comboBox.getSelectedItem().toString();
comboBox.addActionListener(listener);
selectionButton = new JButton("Test (Play)");
selectionButton.addActionListener(listener);
mainPanel.add(comboBox);
mainPanel.add(selectionButton);
}
public JPanel getPanel()
{
return mainPanel;
}
public static Object getSoundSelect()
{
return soundSelect;
}
}
SMListenerClass
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class SMListenerClass implements ActionListener
{
SMPanel play;
File soundFilePlay;
AudioClip soundPlay;
public SMListenerClass(SMPanel smPanel)
{
play = smPanel;
}
public void actionPerformed(ActionEvent arg0)
{
if(SMPanel.soundSelect.equals("1"))
{
soundFilePlay = new File("/Sounds/Railroad_Crossing_Bell.wav");
try
{
soundPlay = Applet.newAudioClip(soundFilePlay.toURL());
}
catch(Exception e)
{
e.printStackTrace();
}
soundPlay.play();
soundPlay.stop();
}
}
}
I am attempting to use java.applet to play to sound, is there a way to fix this or change the code in a way where the sound can play.
Additional notes: I am using Java SDK 8, some of the other solutions on this site would not work for my program. If you need anymore info, just ask.