I'm trying to apply sound today, and the goal in mind was a simple violin tuner. The actionListener
seems repetitive/ How might I optimize it (what I tried just broke everything)? I also noticed the sounds bleed into each other. I don't mind that so much for the different keys (though I'm thinking of a toggle option for this) but it also is the case for the same key, which is undesirable. I'm not sure how to handle that.
/* Author: Luigi Vincent
A simple violin tuner, emits G, D, A, and E sounds to facilitate violin tuning
*/
import javax.swing.*;
import javax.sound.sampled.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class ViolinTuner {
public static void main(String[] args) {
JFrame frame = new JFrame("Violin Tuner");
// get and set icon for the program
ImageIcon icon = new ImageIcon("Images/Icon.png");
frame.setIconImage(icon.getImage());
// Buttons
final JButton G_KEY = new JButton("G");
final JButton D_KEY = new JButton("D");
final JButton A_KEY = new JButton("A");
final JButton E_KEY = new JButton("E");
// Listener to play sounds on click
ActionListener violinSounds = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == G_KEY) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("Sounds/G.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}catch(Exception x) { x.printStackTrace(); }
}
else if (e.getSource() == D_KEY) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("Sounds/D.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}catch(Exception x) { x.printStackTrace(); }
}
else if (e.getSource() == A_KEY) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("Sounds/A.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
}catch(Exception x) { x.printStackTrace(); }
}
else if (e.getSource() == E_KEY) {
try {
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("Sounds/E.wav").getAbsoluteFile());
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.start();
} catch(Exception x) { x.printStackTrace(); }
}
}
};
// Register buttons to listener
G_KEY.addActionListener(violinSounds);
D_KEY.addActionListener(violinSounds);
A_KEY.addActionListener(violinSounds);
E_KEY.addActionListener(violinSounds);
// buttons to panel
JPanel p = new JPanel();
p.add(G_KEY);
p.add(D_KEY);
p.add(A_KEY);
p.add(E_KEY);
// Panel to frame
frame.add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(225, 75);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
};