Thursday, November 5, 2009

Where's my Sound ???

Here's a Handy little tip I just figured out today. So I have a button that plays sound and once if finishes playing it should fire the Event.SOUND_COMPLETE. In this events handler, it resets the position back to the beginning of the clip. Now the problem is once I try to play it again, it doesn't seem to fire the Event.SOUND_COMPLETE event. Have you ever had the issue of your Event.SOUND_COMPLETE not firing properly?? Read on and find out why......



After some debugging, I noticed that every time you pause a sound and play it again, a new SoundChannel is returned. Any event listeners I had applied to the SoundChannel before are disregarded once I pause and play. Instead of :





function playSound():void
{
mySound : Sound = new Sound();
mySound.addEventListener(Event.COMPLETE, soundLoaded);
mySound.load(MY SONG REQUEST);
}

function soundLoaded(e : Event):void
{
myChannel = new SoundChannel();
myChannel.addEventListener(Event.SOUND_COMPLETE, soundComplete);
myChannel = mySound.play();
}

function soundComplete(e : Event):void
{
position = 0;
playChannel()
pauseChannel();
myChannel.addEventListener(Event.SOUND_COMPLETE, soundComplete);
}

function pauseChannel():void
{
myChannel.stop();
position = myChannel.position;
}

function playChannel():void
{
myChannel = mySound.play(position);
}

But It should be :



function playSound():void
{
mySound : Sound = new Sound();
mySound.addEventListener(Event.COMPLETE, soundLoaded);
mySound.load(MY SONG REQUEST);
}

function soundLoaded(e : Event):void
{
myChannel = new SoundChannel();
myChannel.addEventListener(Event.SOUND_COMPLETE, soundComplete);
myChannel = mySound.play();
}

function soundComplete(e : Event):void
{
position = 0;
playChannel();
pauseChannel();
}

function pauseChannel():void
{
myChannel.stop();
position = myChannel.position;
}

function playChannel():void
{
myChannel = mySound.play(position);
myChannel.addEventListener(Event.SOUND_COMPLETE, soundComplete);
}

You need to register the event listener again once you call play. I hope this saves 30 minutes of your day once you start screaming...WHERE'S MY SOUND!!!

2 comments:

  1. thank you Gomez!

    Keep up the good work!!

    ReplyDelete
  2. good stuff

    Since there really is no pausing in Flash I think what it does is that as soon as a sound is done playing in a channel the sound is removed from the channel. That is why each time you play a new channel is given and you have to put the event listener after each time you play.

    You could simplify the code above a bit if you just make single function that does the playing and call this each time.

    So in soundLoaded you just call the function playChannel()

    Also helps if you define mySound and myChannel outside of the functions.

    ReplyDelete