Thursday, March 17, 2011

Sound in flash


Here is short tutorial how to play sound in flash and control it.

Firstly we need to import classes:

import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;

also one more for loading file:
import flash.net.URLRequest;

In this example file will be loaded externally. Of course there is possibility to embed it.

Now, we have to create instance and load file into it:

var mySound:Sound = new Sound();
mySound.load(new URLRequest('sound.mp3'));

Now it's time to play and control it. It's possible to initiate playing sound even if it's not loaded. Flash itself creates stream and buffers it automatically. It may happen that sound won't be played when you call play() method because it's not yet buffered enough:


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

Now we should stop it. Don't ask me why but you cannot stop sound but whole channel

myChannel.stop();

OK, let's go a bit further. Pause option. There's no ready solution. We have to stop channel. Remember to  save progress before.


pausePosition = myChannel.position;
myChannel.stop();

Position is value from 0 to 1 which holds the progress of played track. Now when we have this information we should modify play so that we can continue from saved moment instead of starting from begin.

myChannel = song.play(pausePosition);

While testing you 'll find that you need one more fix. Stop action should reset position


pausePosition = 0;
myChannel.stop();

Let's add one more thing. Volume control. ActionScript3 allows to configure almost every aspect of playing sound. Such complicated functionality needed many classes. That's why for modifing volume we use another class SoundTransform.


myTransform.volume+=VOLUMESTEP;
myChannel.soundTransform = myTransform;

Initially volume is set to 0.5 so you can switch it both ways.

Remember that every time you start playing sound it's sound's transformations are reseted. So to continue playing after pause with same volume level, you have to assign settings


myChannel = song.play(pausePosition);
myChannel.soundTransform = myTransform;







No comments:

Post a Comment