Playing and Stopping Sound in Flash with AS3.0


ActionScript 3 and the timeline

Doing my Flash project for Digital Sound and the Moving Image, I realised that embedding sound in the timeline is not always the way to go, especially if you have an input screen (would use stop() so that the animation does not progress as it waits for user input) and it's possible the user could stay at for any varying length of time, yet the same time, there is a fixed point you know you want this sound to stop without disrupting the rest of the sounds by using a function like SoundMixer.stopall(). Thus, one solution to fixing this is to embed your sound within your ActionScript, as I discovered from sites I would not engage in but are useful to explore.

Firstly, the sound needs to be imported into the Library, but it's also important to ensure it is exported for ActionScript, and given a unique identifier. You can just do this by doubleclicking the space to the right of it usually and typing in a name for it.

Don't put your sound within a keyframe, but create a layer for your ActionScript (ActionScript must be on a separate layer, it can't be created on an object layer) and create a keyframe where you want your sound to start. You can use the following code to call the sound you want to start ('mySound' here):

var myChannel:SoundChannel = new SoundChannel();
var mySound:Sound = new mySound(); 
myChannel = mySound.play(0);

I believe you can have play as 0,0 if you wish which basically starts the sound file from 0 and does not loop. In the above case, the sound would most likely loop. So anyway, you've coded it so your sound will play when it reaches where you placed your keyframe on the timeline. You want it to stop somewhere.

In order to stop it, you can create another keyframe where the sound is supposed to stop playing on the same ActionScript layer. Using the following code, this will make the 'SoundChannel' called 'myChannel' earlier stop.

myChannel.stop();

I had no problems utilising this code in my project at all, although when I tried to turn the volume of the sound down, this was unsuccessful and I eventually just changed the volume of the sound file overall. This solution works great for me within a project, but if you utilise this method and try to load in a new .swf, it will play continuously - in such a case embedding in the timeline is likely a better solution, however I have not tried it.

Alternatively, I attempted to use such a solution, but it had no effect at all which was extremely strange. If anyone has any idea, feel free to send me a line.