Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.sound.midi.*;
- public class SingleButtonWithSound implements ActionListener {
- JButton button = new JButton("ding");
- public static void main(String[] args) {
- SingleButtonWithSound b = new SingleButtonWithSound();
- b.createLayout();
- }
- private void createLayout() {
- JFrame frame = new JFrame();
- JPanel panel = new JPanel();
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- panel.setLayout(new GridBagLayout());
- GridBagConstraints gbc = new GridBagConstraints();
- gbc.gridwidth = GridBagConstraints.REMAINDER;
- gbc.fill = GridBagConstraints.HORIZONTAL;
- panel.add(button, gbc);
- button.addActionListener(this);
- frame.add(panel);
- frame.pack();
- frame.setSize(300, 400);
- frame.setVisible(true);
- }
- public void actionPerformed(ActionEvent event) {
- playSound();
- }
- private static void playSound() {
- try {
- Sequencer player = MidiSystem.getSequencer();
- player.open();
- Sequence seq = new Sequence(Sequence.PPQ, 4);
- Track track = seq.createTrack();
- ShortMessage a = new ShortMessage();
- a.setMessage(144, 1, 44, 100);
- MidiEvent noteOn = new MidiEvent(a, 0);
- track.add(noteOn);
- ShortMessage b = new ShortMessage();
- b.setMessage(128, 1, 44, 100);
- MidiEvent noteOff = new MidiEvent(b, 1);
- track.add(noteOff);
- player.setSequence(seq);
- player.start();
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment