您正在尝试在 newbox 创建之前将事件侦听器添加到它。尝试如下:
// mySound should be availible in scope
var mySound:testSound = new testSound();
// newBox also
var newBox:right_box;
// here is a channel for you
var channel: SoundChannel;
// ok this adds the first listener...
leftBox.addEventListener(MouseEvent.CLICK, addBox);
function addBox(event:MouseEvent):void {
newBox = new right_box();
addChild(newBox);
newBox.x = 0;
newBox.y = 0;
newBox.width = leftBox.width;
newBox.height = leftBox.height /2;
// you should add listener here...
newBox.addEventListener(MouseEvent.CLICK, playSound);
// you have to avoid multiple newBoxes on each other and
// leaving the older ones under..
// So stop listening to the newBox generating event:
leftBox.removeEventListener(MouseEvent.CLICK, addBox);
}
function playSound(event:Event){
channel = mySound.play();
// On next click you want sound to stop so
// First remove the old listener to avoid play over:
newBox.removeEventListener(MouseEvent.CLICK, playSound);
// and hook listener to stop method
newBox.addEventListener(MouseEvent.CLICK, stopSound);
}
function stopSound(event:Event){
channel.stop();
// On next click you want to remove newBox
// First remove the old listener to avoid play over:
newBox.removeEventListener(MouseEvent.CLICK, stopSound);
newBox.addEventListener(MouseEvent.CLICK, removeNewBox);
}
function removeNewBox(event:Event){
// First remove the listener :
newBox.removeEventListener(MouseEvent.CLICK, removeNewBox );
removeChild(newBox); // now remove from display list
newBox = null; // make contents eligible for garbage collection
}