Reputation: 1
What I'm trying to do is loop a sound on a mouse down event and then on mouse up event I want to finish what ever iteration it's on and stop the loop.
This logic below should work, but I have no idea why it's not.
import flash.events.MouseEvent;
import flash.media.Sound;
import flash.events.Event;
import flash.media.SoundChannel;
//ExplosionSound is .wav file linked in my library.
var s:Sound=new ExplosionSound();
var sc:SoundChannel = new SoundChannel();
stage.addEventListener(MouseEvent.MOUSE_DOWN, loopSound);
stage.addEventListener(MouseEvent.MOUSE_UP, stopLoop);
function loopSound(e:MouseEvent):void {
sc=s.play(0,9999);
}
function stopLoop(e:MouseEvent):void {
sc.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
}
function soundCompleteHandler(e:Event):void{
sc.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
sc.stop();
}
I could just put sc.stop(); in my stopLoop() function, but that stops the sound immediatly.
What I need, for example is: say you have a machine gun shooting, and when you stop shooting it the last bullet sound does not stop immediately, it finishes.
Hope this makes sense.
Thank you for all your help.
Upvotes: 0
Views: 174
Reputation: 18860
the SOUND_COMPLETE "never" gets fired when you loop your sound - would only get fired after the 9999th time looping. so you have to work around this:
import flash.events.MouseEvent;
import flash.media.Sound;
import flash.events.Event;
import flash.media.SoundChannel;
//ExplosionSound is .wav file linked in my library.
var s:Sound=new ExplosionSound();
var sc:SoundChannel = new SoundChannel();
var isMouseDown:Boolean = false;
stage.addEventListener(MouseEvent.MOUSE_DOWN, loopSound);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
function loopSound(e:MouseEvent):void {
isMouseDown = true;
playSound();
}
function playSound():void
{
sc=s.play(0);
sc.addEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
}
function onMouseUpHandler(e:MouseEvent):void {
isMouseDown = false;
}
function soundCompleteHandler(e:Event):void{
sc.removeEventListener(Event.SOUND_COMPLETE, soundCompleteHandler);
sc.stop();
if (isMouseDown)
{
playSound();
}
}
just play the sound once on mousedown (but keep a flag whether or not the mouse is still down) and add a SOUND_COMPLETE handler. if the sound finished and the mouse is still down, replay the sound. if the mouse button is released, the flag gets reset and the sound won't replay when finished.... tataaaaa
Upvotes: 1