Krain45 Krain45 - 11 months ago 62
Java Question

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?

Answer Source

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;

    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

    public void paint(Graphics g){
        //display message as to which key to press to play a sound

    public void keyPressed(KeyEvent K){

        char X = K.getKeyCode();
        if(X == 'K'); //play kick.wav when K is pressed

        if(X == 'S'); //play snare.wav when S is pressed

        if(X == 'T'); //play tom.wav when T is pressed

        if(X == 'O'); //play hat_open.wav when O is pressed

        //write if statements for the rest of the Keys


    public void keyReleased(KeyEvent K){}

    public void keyTyped(KeyEvent K){}


Hope this will help you understand.