Control sound volume.

In this tutorial we will learn how to control the volume of the sound that we play in Flash.Adding sound to your site can improve the user experience but not offering a way to control the sound could irritate the user and make him go away forever, and we don’t want that. We will build a slider that will help us to increase or decrease the sound volume and will learn how to load mp3s that we import in the Flash Library.

1. Create a new file by going to File > New select Flash file (ActionScript 3.0) and click Ok.

2. On the stage draw a rectangle width: 100 px, height: 23 px, color: black and stroke: none. With the rectangle selected press F8 and convert it to a MovieClip. Set its name to track_mc and registration point to top left and click Ok. In the Property Inspector set its instance name to track_mc.

3. Double click on the track_mc MovieClip to edit it. Lock the current layer. Insert a new one, double click on its name and rename it slider. Draw a rectangle width: 10, height: 23, color: #FF6600 and set the stroke to none. Position the rectangle in the middle of the track_mc MovieClip. With the rectangle selected press F8 and convert it to a MovieClip. Set its name to slider_mc and registration point to top left and click Ok. In the Property Inspector set its instance name to slider_mc.

4. Go back to the main stage by clicking on the Scene 1 button. Double click on the layer name and name it track. This is what you should have on the stage until now.

5. Lock the track layer and insert a new one, name the new layer buttons. We will make a play and a stop button. On the button layer draw a rectangle: width: 23, height: 23, color: #FF6600 and set the stroke to none. With the rectangle selected press F8 and convert it to a MovieClip. Set its name to stop_btn and click Ok. In the Property Inspector set its instance name to stop_btn.

6. On the same layer draw a triangle same size and color like in step 5.Convert it to a MovieClip name it play_btn and set its instance name to play_btn. Position the MovieClips like in the picture:

7. Let’s import a sound to the Library. Go to File > Import > Import to Library browse to your local hard drive and select the mp3 that you want to import.

8. Press Ctrl+L to open the Library. Select your imported mp3, right click and chose Linkage. In this panel check Export for ActionScript, set the Class name to Song and click Ok. In the window that appears click Ok. This is the name that we give to the class that is associated with the imported mp3.

9. Insert a new layer and name it actions. Select frame 1 of this layer and press F9 to open the ActionScript panel. Copy and paste the code from below.

// Code for loading, playing and stopping sound
var song:Song = new Song();
var myChannel:SoundChannel = new SoundChannel();
var soundVol:SoundTransform = new SoundTransform();
play_btn.buttonMode = true;
stop_btn.buttonMode = true;
play_btn.addEventListener(MouseEvent.CLICK,startPlay);
stop_btn.addEventListener(MouseEvent.CLICK,stopPlay);
function startPlay(event:MouseEvent):void {
myChannel=song.play(0,10);
play_btn.removeEventListener(MouseEvent.CLICK,startPlay);
}
function stopPlay(event:MouseEvent):void {
myChannel.stop();
play_btn.addEventListener(MouseEvent.CLICK,startPlay);
}
// Code that handles the sound volume
var ratio_volume:Number;
var trackBounds:Rectangle = track_mc.getBounds(track_mc);
var xPos:Number = trackBounds.x;
var yPos:Number = trackBounds.y;
var widthPos:Number = trackBounds.width-track_mc.slider_mc.width;
var heightPos:Number = 0;
var bounds:Rectangle = new Rectangle(xPos,yPos,widthPos,heightPos);
track_mc.slider_mc.x = widthPos;
track_mc.mouseEnabled = false;
track_mc.slider_mc.buttonMode = true;
track_mc.slider_mc.addEventListener(MouseEvent.MOUSE_DOWN,dragSlider);
stage.addEventListener(MouseEvent.MOUSE_UP,stopSlider);
function dragSlider(event:MouseEvent):void {
event.target.startDrag(false,bounds);
addEventListener(Event.ENTER_FRAME,setVolume);
}
function stopSlider(event:MouseEvent):void {
track_mc.slider_mc.stopDrag();
removeEventListener(Event.ENTER_FRAME,setVolume);
}
function setVolume(event:Event):void {
ratio_volume = track_mc.slider_mc.x/widthPos;
soundVol.volume = ratio_volume;
myChannel.soundTransform = soundVol;
}

Press Ctrl + Enter to test your movie. Click the play_btn to start the sound; you can control the volume by dragging the slider.

Let’s look at the code.

I divided the code in two parts: code that is responsible for loading, playing and stopping the sound and code that handles the volume.

I will not explain the first part because I did that in Loading, playing and stopping sounds tutorial. What is different is the method used for loading the sound. In this tutorial we load the sound from the library and in that the sound was loading from external source.

We load the sound from the library by creating an instance (song) of the Song class that we have creating. This class extends the Sound class and because that the song object will inherit all the properties and methods of the Sound class.

In the second part: code that handles the sound volume first we declare a variable that will hold the sound volume (ratio_volume).

In the next 6 lines we get the bounds (x position, y position, width and height) of the track_mc and use those values to calculate the bounds, limits for the slider_mc. The bounds will establish the coordinates in witch we can move the slider.

Next we set the initial position of the slider (track_mc.slider_mc.x = widthPos; ), enabled the butttonMode property (will show the hand cursor when your cursor it’s over the slider) and prevent track_mc to receive mouse events (track_mc.mouseEnabled = false ;).

The function dragSlider handles the MOUSE_DOWN event added to the slider_mc. When the event occurs the slider can be dragged. Inside the function we add an ENTER_FRAME event, event that is handled by the setVolume function.

stopSlider function handles the MOUSE_UP event, when this event occurs the slider can’t be dragged .

Inside the setVolume function is where we actually control the volume. First we set the ratio_volume variable to be equal with the ratio of the slider x position and the width of the track. Add the result to the volume property of the SoundTransform object and the modification to take place we add the SoundTransform object to the soundTransform property of the channel.

This is all. I hope that you enjoyed the tutorial. If you have questions, suggestions, doubts about the tutorial don’t hesitate to comment.

Until next time have fun learning Flash.

To download the source file go to Control sound volume.

Comments

Unknown said…
I followed your instructions, but when I exported, I got the following errors and zero functionality:

1046: Type was not found or was not a compile-time constant: Song.
Sorin said…
Go back to step 8 and make sure that you have fallowed exactly the instructions. That should fix your problem. If not try downloading the source file.
Unknown said…
I got all this

**Error** Scene=Scene 1, layer=actions, frame=1:Line 2: The class or interface 'Song' could not be loaded.
var song:Song = new Song();

**Error** Scene=Scene 1, layer=actions, frame=1:Line 3: The class or interface 'SoundChannel' could not be loaded.
var myChannel:SoundChannel = new SoundChannel();

**Error** Scene=Scene 1, layer=actions, frame=1:Line 4: The class or interface 'SoundTransform' could not be loaded.
var soundVol:SoundTransform = new SoundTransform();

**Error** Scene=Scene 1, layer=actions, frame=1:Line 12: The class or interface 'MouseEvent' could not be loaded.
function startPlay(event:MouseEvent):void {

**Error** Scene=Scene 1, layer=actions, frame=1:Line 17: The class or interface 'MouseEvent' could not be loaded.
function stopPlay(event:MouseEvent):void {

**Error** Scene=Scene 1, layer=actions, frame=1:Line 24: The class or interface 'Rectangle' could not be loaded.
var trackBounds:Rectangle = track_mc.getBounds(track_mc);

**Error** Scene=Scene 1, layer=actions, frame=1:Line 29: The class or interface 'Rectangle' could not be loaded.
var bounds:Rectangle = new Rectangle(xPos,yPos,widthPos,heightPos);

**Error** Scene=Scene 1, layer=actions, frame=1:Line 37: The class or interface 'MouseEvent' could not be loaded.
function dragSlider(event:MouseEvent):void {

**Error** Scene=Scene 1, layer=actions, frame=1:Line 42: The class or interface 'MouseEvent' could not be loaded.
function stopSlider(event:MouseEvent):void {

**Error** Scene=Scene 1, layer=actions, frame=1:Line 45: The class or interface 'Event' could not be loaded.
function setVolume(event:Event):void {

Total ActionScript Errors: 10 Reported Errors: 10
Sorin said…
Are you using ActionScript 3? Download the sources file and see there how is done.
The script works just fine.
Anonymous said…
There is a typo it seems, in the script. Variable song should be of "Sound" class and not "Song" class.

Apart from this, the application works good.
Sorin said…
There is no typo, if it was the script didn’t work. Variable song should be of type Song because the Song class witch I defined extends the Sound class and inherits all its characteristics.
Anonymous said…
Thank you so very much. This worked perfectly.

Would you happen to know if it is possible to have the song play automatically upon the page loading?

The user could then decide to turn off or adjust the volume.

Thank you again for sharing.

-Sergio
Sorin said…
Hi Sergio,
Sure we can set the song to play automatically. Add this line of code:
myChannel=song.play();
after this line var soundVol:SoundTransform = new SoundTransform();
This will cause other problems. If the user clicks the play button the song will start play again and you will hear two songs play in the same time. This issue can be easy solved by showing only the stop button .When the user clicks on stop button the sound stops and the play button replace the stop button. Is the same approach that I have used in the Loading, playing and stopping sounds in AS 3.0. download the source file from that tutorial and see about what I’m talking.
Anonymous said…
Worked fine for me. One thing I would suggest is removing your event listener where stopDrag() is deployed. Save some memory!
Sorin said…
I was not thinking on saving memory when I write this tutorial, but you have right I should remove it. Thanks
Anonymous said…
Thanks for the tutorial! All is great! However I can't use action script 3.0 in my project. Could you rewrite your code for action script 2.0?

With great hope on you, Max
Sorin said…
Hi Max,
Sorry but I’m not coding in as2 anymore. Make a search on Google or browse thru files from ffiles.com, for sure you will find a volume controller that use as2.
Anonymous said…
This is Simply Excellent...Marvelous Job !!!

I was just searching for this kinda AS3. There are hell lot of tutorial and example in the Internet, but I found this one amazing. No import of Sound libraries or this and that kind libraries. That's why I will this as a KISS...means Keep It Simple and Straight.

Thanks a Ton dude !!!
Anonymous said…
Hey, I adapted your code and it works great, but I have an issue. I also added a Left and Right button that increases the "levelHeight" (your ratio_volume) by increments of 10% (that's the whole "Math.round" code. My issue is that those buttons won't activate until I at least click on sliderMC.handle (track_mc.slider_mc).

sliderMC.right.addEventListener(MouseEvent.CLICK, onRight);
function onRight(evt:MouseEvent):void {
if ( (Math.round(levelHeight*100)-6) <= 90){
sliderMC.handle.x += 86;
} else {
sliderMC.handle.x += 0;
}
}

sliderMC.left.addEventListener(MouseEvent.CLICK, onLeft);
function onLeft(evt:MouseEvent):void {
if ( (Math.round(levelHeight*100)-6) >= 10){
sliderMC.handle.x -= 86;
} else {
sliderMC.handle.x -= 0;
}
}
Sorin said…
Hi Larry
Sorry to disappoint you but I don’t have time to debug your code. Try to find an as2 example (if you haven’t find an as3 example) that does what you want and adapt that to your needs.
Steve F said…
Hi, I know this is an old thread, but I am having a problem with the tutorial. When I run the flash, I get the following errors. Well, its more like 1 error repeated as many times as track_mc is referenced.

1120: Access of undefined property track_mc.

I have track_mc and slider_mc in the library, and slider_mc is a symbol within track_mc. What am I doing wrong?
Sorin said…
Hi Steve,
You probably haven’t set its instance name to track_mc in the Property Inspector (step 2 of the tutorial). Take a look at the source files.
Hugo said…
Thank you for this tutorial... really save me a lot of time coding. Great work!

Popular posts from this blog

Photo gallery (AS 3.0).

ActionScript 3 button that stay in the down state.

Custom Scrollbar