joxaren

SingleButtonWithSound

Aug 22nd, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import javax.sound.midi.*;
  6.  
  7. public class SingleButtonWithSound implements ActionListener {
  8.  
  9.     JButton button = new JButton("ding");
  10.  
  11.     public static void main(String[] args) {
  12.         SingleButtonWithSound b = new SingleButtonWithSound();
  13.         b.createLayout();
  14.     }
  15.  
  16.     private void createLayout() {
  17.         JFrame frame = new JFrame();
  18.         JPanel panel = new JPanel();
  19.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  20.         panel.setLayout(new GridBagLayout());
  21.  
  22.         GridBagConstraints gbc = new GridBagConstraints();
  23.         gbc.gridwidth = GridBagConstraints.REMAINDER;
  24.         gbc.fill = GridBagConstraints.HORIZONTAL;
  25.  
  26.         panel.add(button, gbc);
  27.         button.addActionListener(this);
  28.         frame.add(panel);
  29.         frame.pack();
  30.         frame.setSize(300, 400);
  31.         frame.setVisible(true);
  32.     }
  33.  
  34.     public void actionPerformed(ActionEvent event) {
  35.         playSound();
  36.     }
  37.  
  38.     private static void playSound() {
  39.         try {
  40.             Sequencer player = MidiSystem.getSequencer();
  41.             player.open();
  42.             Sequence seq = new Sequence(Sequence.PPQ, 4);
  43.             Track track = seq.createTrack();
  44.  
  45.             ShortMessage a = new ShortMessage();
  46.             a.setMessage(144, 1, 44, 100);
  47.             MidiEvent noteOn = new MidiEvent(a, 0);
  48.             track.add(noteOn);
  49.  
  50.             ShortMessage b = new ShortMessage();
  51.             b.setMessage(128, 1, 44, 100);
  52.             MidiEvent noteOff = new MidiEvent(b, 1);
  53.             track.add(noteOff);
  54.  
  55.             player.setSequence(seq);
  56.             player.start();
  57.  
  58.         } catch (Exception ex) {
  59.             ex.printStackTrace();
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment