Playing Sounds with AS3

Playing sounds using ActionScript 3.0 is not as simple as we hoped it to be as it requires using more than one class to perform even the simplest of tasks relating to sound such as pausing or changing the sound volume. This tutorial will teach you all the basics you need to learn how to start playing local and external sounds in Flash.

This tutorial will be divided into the following sections:

  1. Introduction to Sound Related Classes.
  2. Playing an Internal Sound.
  3. Playing an External Sound.
  4. Stopping a Sound.
  5. Pausing a Sound.
  6. Changing Sound Volume.

Introduction to Sound Related Classes

Sounds in ActionScript 3.0 are manipulated through the collaborative work of several classes together. This is a much more complex structure than previous versions of ActionScript, but it is argued that this format will provide you with greater control and the ability to micro manage sounds. Here are the relevant classes related to sounds:

  1. Sound Class - This is the main class in which a sound will actually reside. This class is the starting point of any sound related program and is used to start playing a sound.
  2. SoundChannel Class - A sound can be played through a sound channel which provides additional controls over a sound object, the most basic of these additional controls is the ability to stop the playback of a sound.
  3. SoundTransform Class - This class is responsible for altering sound volume and sound panning (manipulating the balance between the left and right speakers).
  4. SoundMixer Class - This class has global control over all sounds played in the Flash player. It's most basic function is to stop all playing sounds regardless of source.

We will provide you with practical examples on how to use all of these classes below, except for the SoundMixer Class as it is not required to carry out a basic sound function and instead it collectively controls all sounds playing in Flash. Review the ActionScript reference for more help on this class.

Playing an Internal Sound File

Flash is capable of only playing .mp3 files and no other sound format. Playing an .mp3 file is an easy task that can be performed using the Sound Class. The Sound Class can play internal sounds (mp3 files imported into an FLA file) or external sounds (mp3 files loaded by the SWF at run time). We are going to start by playing an internal .mp3 file imported into the Flash movie.

To follow this tutorial you will need to have an .mp3 file to play. You can legally download some free sound tracks from this website. Download any track and save it on your computer.

Once you have your mp3 file ready, open up Flash and creating a new FLA in AS3 Format, and then go through File>Import>Import to Library, browse for your .mp3 file and then click on Open.

AS3 Sound Class

Once your file is imported, open your library (Ctrl+L) to find your sound file in there. We are going to make this file available for ActionScript by editing its Linkageproperties, right-click the sound file, select Linkage to open up the linkage window. Check the box for Export for ActionScript and change the Class name toMyFavSong. Press OK, you should get the same warning message you get for creating any Class with external definition file. Simply press OK to continue. That should export our sound file as an ActionScript Class called MyFavSong.

Linkage Window - AS3 Sound

We now have our .mp3 file readily available for ActionScript. It is time to start coding the ActionScript. Right-click the only frame you have on the timeline and selectActions to open up the Actions panel.

To play our sound we need to create a new instance of our sound class and then use the Sound Class method .play() to play it. The code below is pretty self explanatory:

var mySound:Sound = new MyFavSong(); 
mySound.play();
The Sound Class  .play() method is used to play a sound. By default it plays the sound from its beginning, however you can start it from any other point by specifying the starting to position in milliseconds (Example:  mySound.play(150)).

Test your movie now (Ctrl+Enter) to hear your sound file playing!

Playing an External Sound File

Playing an external sound file is easier than playing an internal sound file because you are not required to import your file or create a class out of it.

You can create a new FLA for this version, save your FLA somewhere on your desktop, then put your .mp3 file in the same folder, and rename it to myFavSong.mp3.

Sound and FLA Same Directory

Now back to the FLA, open up the Actions panel to start coding. We are simply going to create a new generic instance of the Sound Class, and then will use the .load()method to load the external file. Finally we will use the .play() method to play the sound:

var mySound:Sound = new Sound();
mySound.load(new URLRequest("myFavSong.mp3"));
mySound.play();
The Sound Class  .load() method is used to load an external .mp3 file. The URL must be specified as an instance of the URLRequest Class. Refer to the ActionScript Reference for more info on the URLRequest Class.

You can test your movie now to hear your sound playing!

Stopping A Sound

In addition the ability to play a sound, you will obviously also want to know how to stop your sound after you play it. The Sound Class does not have a method for stopping a sound. The SoundChannel Class must be used to perform that task. A SoundChannel is a class that is used to hold a raw sound object and then manipulate it using the methods and properties of the SoundChannel Class. The methods and properties you should be aware of are:

  • .stop() - this method stops the sound playing through the channel.
  • .position - this property is used to retrieve the current playback position of the sound playing through the channel.
  • .soundTransform - this property is used to set and retrieve sound transformations such as volume and panning.

We are going to continue working with the FLA that loads an external sound file and will create a button that stops the sound when clicked. In that same FLA, access theComponents Panel (Window>Components) and drag and instance of the Button Component under the User Interface category. Access the Properties Inspector and assign the instance name stop_btn to this button. You can change the label of the button to say Stop by accessing the Parameters tab.

AS3 Sounds - Stop Button

We will now make clicking on this button stop our sound. Right-click the only frame you have on the timeline and select Actions to open up the Actions Panel. You should have this code from our previous section:

var mySound:Sound = new Sound();
mySound.load(new URLRequest("myFavSong.mp3"));
mySound.play();

We will first create a new variable to hold an new instance of the SoundChannel channel:

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
mySound.load(new URLRequest("myFavSong.mp3"));
mySound.play();

We need this SoundChannel instance to capture the sound when it starts playing so that we can manipulate it through the channel. To do this, replace the line that tells the sound to play with the line highlighted below:

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
mySound.load(new URLRequest("myFavSong.mp3"));
myChannel = mySound.play();

Our SoundChannel now has our sound playing in it. We will register an event listener with our button to tell this channel to stop when the button is clicked using the SoundChannel .stop() method.

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
mySound.load(new URLRequest("myFavSong.mp3"));
myChannel = mySound.play();

stop_btn.addEventListener(MouseEvent.CLICK, onClickStop);

function onClickStop(e:MouseEvent):void{
myChannel.stop();
}
Please check our  AS3 Event Handling Tutorial to learn more about adding basic interactivity using AS3.

You can test your movie now to hear your sound playing automatically at the movie starts, when you click on the button the sound should stop.

Of course once you stop your sound there is no way to get it to play again using our code. Doing that is covered in our next section along with the trick on how to create apause button.

Pausing a Sound

ActionScript does not provide a method with a .pause functionality, the functionality to pause a song and play it again from that specific point will require the manual retrieval of the position of the song before it was stopped and then playing it back from that point. We have talked about the SoundChannel .position property and the ability to play a sound from a specific position using the .play() method. We are going to use these together to complete this part.

Start off by adding a new button to your scene, access the Components Panel and add a new button to the scene, set the instance name play_btn to it and change its label to Play. Update the label of your previous button so that it says Pause instead of Stop and change its instance name from stop_btn to pause_btn. You should end up with two buttons in your scene.

AS3 Sounds - Play Pause Buttons

Now back to ActionScript. The first thing to do is delete all the code related to the stop_btnRemove the code highlighted below.

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
mySound.load(new URLRequest("myFavSong.mp3"));
myChannel = mySound.play();

stop_btn.addEventListener(MouseEvent.CLICK, onClickStop);

function onClickStop(e:MouseEvent):void{
myChannel.stop();
}

In order for our pause button to function we need to create a variable to store the last position of our sound file. We can easily create this variable and set the value 0 as its initial value, we will name this variable lastPosition:

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
var lastPosition:Number = 0;
mySound.load(new URLRequest("myFavSong.mp3"));
myChannel = mySound.play();

Now we will make our Pause Button, retrieve this value when it is clicked, and instantly stop the sound afterwards. We are going to use an event handler similar to the one we used for our stop button:

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
var lastPosition:Number = 0;
mySound.load(new URLRequest("myFavSong.mp3"));
myChannel = mySound.play();

pause_btn.addEventListener(MouseEvent.CLICK, onClickPause);

function onClickPause(e:MouseEvent):void{
lastPosition = myChannel.position;
myChannel.stop();
}

We will now let our Play Button play the sound file from that last position. You should remember that the .play method is an instance of the Sound Class and that it should be reinserted into the SoundChannel again:

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
var lastPosition:Number = 0;
mySound.load(new URLRequest("myFavSong.mp3"));
myChannel = mySound.play();

pause_btn.addEventListener(MouseEvent.CLICK, onClickPause);

function onClickPause(e:MouseEvent):void{
lastPosition = myChannel.position;
myChannel.stop();
}

play_btn.addEventListener(MouseEvent.CLICK, onClickPlay);

function onClickPlay(e:MouseEvent):void{
myChannel = mySound.play(lastPosition);
}

That should do it. You can test your movie now (Ctrl+Enter) and try out your pause and play buttons.

You can download the source file of this  FLA from here.

Changing the Volume

In the final section of this tutorial you will learn how to alter the volume of a SoundChannel. Changing the volume requires using the SoundTransform Class and the theSoundChannel .soundTransform property.

The SoundTransform Class has various properties, the most important one to us is the .volume property. Using the SoundTransform is pretty simply, all we have to do is create an instance of it, set its properties, and then set it as the value of the .soundTransform property of our targeted SoundChannel.

We are going to do this now. Start off by creating a new instance of the SoundTransform Class:

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
var myTransform = new SoundTransform();
var lastPosition:Number = 0;
mySound.load(new URLRequest("myFavSong.mp3"));
myChannel = mySound.play();

pause_btn.addEventListener(MouseEvent.CLICK, onClickPause);

function onClickPause(e:MouseEvent):void{
lastPosition = myChannel.position;
myChannel.stop();
}

play_btn.addEventListener(MouseEvent.CLICK, onClickPlay);

function onClickPlay(e:MouseEvent):void{
myChannel = mySound.play(lastPosition);
}

We will now set the value of the .volume property of this instance. The volume property can have any floating value between 1 and 0 where 1 means max volume and zero means mute. We are going to set the volume to medium by using 0.5 as our value:

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
var myTransform = new SoundTransform();
var lastPosition:Number = 0;
mySound.load(new URLRequest("myFavSong.mp3"));
myChannel = mySound.play();
myTransform.volume = 0.5;

pause_btn.addEventListener(MouseEvent.CLICK, onClickPause);

function onClickPause(e:MouseEvent):void{
lastPosition = myChannel.position;
myChannel.stop();
}

play_btn.addEventListener(MouseEvent.CLICK, onClickPlay);

function onClickPlay(e:MouseEvent):void{
myChannel = mySound.play(lastPosition);
}

We will now set this transform as the .soundTransform property of our SoundChannel:

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
var myTransform = new SoundTransform();
var lastPosition:Number = 0;
mySound.load(new URLRequest("myFavSong.mp3"));
myChannel = mySound.play();
myTransform.volume = 0.5;
myChannel.soundTransform = myTransform;

pause_btn.addEventListener(MouseEvent.CLICK, onClickPause);

function onClickPause(e:MouseEvent):void{
lastPosition = myChannel.position;
myChannel.stop();
}

play_btn.addEventListener(MouseEvent.CLICK, onClickPlay);

function onClickPlay(e:MouseEvent):void{
myChannel = mySound.play(lastPosition);
}

You must always remember to set the .soundTransform AFTER you insert a sound object into your channel and NOT before. You can test your movie now to hear the volume lower. However, you will notice that when you press pause and then play again, the volume will go high again. This is because when you insert a new sound into a channel all the sound transformations are erased. We can fix that by setting the .soundTransform property again from within the onClickPlay event handler this way:

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
var myTransform = new SoundTransform();
var lastPosition:Number = 0;
mySound.load(new URLRequest("myFavSong.mp3"));
myChannel = mySound.play();
myTransform.volume = 0.5;
myChannel.soundTransform = myTransform;

pause_btn.addEventListener(MouseEvent.CLICK, onClickPause);

function onClickPause(e:MouseEvent):void{
lastPosition = myChannel.position;
myChannel.stop();
}

play_btn.addEventListener(MouseEvent.CLICK, onClickPlay);

function onClickPlay(e:MouseEvent):void{
myChannel = mySound.play(lastPosition);
myChannel.soundTransform = myTransform;
}

That should do it. Test your movie again to have your volume set once and for all even for your pause and play buttons!

This concludes our tutorial. I hope that you learnt something new about using Sounds in AS3. Feel free to post any questions you have at the Oman3D Forum.

- End of Tutorial

你可能感兴趣的:(Playing Sounds with AS3)