Playing External Audio Files

There are a lot of similarities in playing external audio file as there is in importing external images and SWF files.

You will need to create a Sound object (which has properties and methods for working with audio files) and a URLRequest object to load the audio file.

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

Stoping a Sound from Playing

However, we do not have the ability to stop the audio file from playing if we need it to. Therefore we add a SoundChannel object, and assign the channel the result of playing the audio file.

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

This will allow us to use the myChannel.stop() method when we want to stop the audio file from playing.

Pausing a Sound

To pause a sound, we have to know where is was in the playback, so it can be continue from that location. We will need to add a new variable to store that information.

var mySound:Sound = new Sound();
var myChannel:SoundChannel = new SoundChannel();
var lastPosition:Number = 0;	// set up a variable to store the playback location
mySound.load(new URLRequest("mySong.mp3"));
myChannel = mySound.play();
function onPauseClick(e:MouseEvent): void { lastPosition = myChannel.position; // store where the audio file stopped
myChannel.stop();
}
function onClickPlay(e:MouseEvent):void{
myChannel = mySound.play(lastPosition); // resume playing from the last position
}