Attaching Sound to Keypress

Pup 100,

You’re on the right track. You must click in the page to give the page focus. I could be wrong, but I don’t think there’s any way around that. A “click to start” button would solve this.

A couple of things:

  1. For efficiency and organization, I would not define the sound object within the conditional code. I would define all sound objects either in the onClipEvent(load) or just in a single frame on the root time line.

  2. One challenge of your code is that the sound will continue to activate as long as the keypress is held down. If the presenter only wants it to activate once, you need to provide code that will not allow it to activate again until the key is released and pressed again. For example:


onClipEvent(load) {
//Sound Objects
kick1=new Sound(this); 
kick1.attachSound("kick01"); 

kick2=new Sound(this); 
kick2.attachSound("kick02"); 

kick3=new Sound(this); 
kick3.attachSound("kick03"); 
//
//Create a listener that detects when a key is released
myKeyUp = new Object();
myKeyUp.onKeyUp = function() {
	releaseVar=0;
}
Key.addListener(myKeyUp);
	
}//END OF Clip Event Load
//
onClipEvent(enterFrame) {
//You could shorted the coding with the following.
_root.myKeyCode=Key.getCode();
keyPressed=Key.getCode();
//
//
if(Key.isDown(65) && releaseVar!=1){ // key "f"
	releaseVar=1;
	_root.kick1.start();
}
//
if(Key.isDown(83) && releaseVar!=1){ // key "s"
	releaseVar=1;
	_root.kick2.start();
} 
//
if(Key.isDown(68) && releaseVar!=1){ // key "d"
	releaseVar=1;
	_root.kick3.start();
}
}//END