Search code examples
javaevent-handlingapplet

How to play a sound when a specific key is pressed?


I'm trying to create a drums applet. So every part of the drum has corresponding keys in the keyboard and if you press it, a sound plays. How do I play a sound using keys?


Solution

  • Okay. So you need the samples of the different drum kit sound, eg. Kick, Snare, Hihat, crash, etc. It's best if you have them in a .wav format. So what you've got to do is using Event Handling, play the corresponding audio when a key is pressed. Make sure all the audio samples are in the same directory as he current project is. Even though writing a code and just doing your homework for you is not a policy to be followed here, I'll write a structure that will explain the thing to you.

    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class DrumApplet extends Applet implements KeyListener{
    
        //declaring Audio variables
        AudioClip kick, snare, hat_close, hat_opem, crash, tom;
    
        @Override
        public void init(){
            kick = this.getAudioClip(getDocumentBase(), "kick.wav");
            snare = this.getAudioClip(getDocumentBase(), "snare.wav");
            //load all other audio samples
    
            addKeyListener(this); //to detect the press of a key
        }
    
        @Override
        public void paint(Graphics g){
            //display message as to which key to press to play a sound
        }
    
        @Override
        public void keyPressed(KeyEvent K){
    
            char X = K.getKeyCode();
            if(X == 'K')
            kick.play(); //play kick.wav when K is pressed
    
            if(X == 'S')
            snare.play(); //play snare.wav when S is pressed
    
            if(X == 'T')
            tom.play(); //play tom.wav when T is pressed
    
            if(X == 'O')
            hat_open.play(); //play hat_open.wav when O is pressed
    
            //write if statements for the rest of the Keys
    
            repaint();
        }
    
        @Override
        public void keyReleased(KeyEvent K){}
    
        @Override
        public void keyTyped(KeyEvent K){}
    
    }
    

    Hope this will help you understand.