Flash Tutorial: How to Add Sound or Music Using Actionscript 3

Flash Tutorial: How to Add Sound or Music Using Actionscript 3

By Steve on October 28, 2010

Flash Tutorial: How to Add Sound or Music Using Actionscript 3

Actionscript 3 – Adding sound or music to Flash files

If you want to add sounds or music to a Flash file using only Actionscript 3, this is how you do it:

1. First, you need to import a sound file into your Library, and then allow it to export by actionscript. Call the class something relevant, for example bg_music. The Base class should be flash.media.Sound.

2. In your actionscript layer we first need to allow Flash to import the basic sound class. Near the start of your AS write:
import flash.media.Sound;
import flash.media.SoundChannel;

3. Next you need to create a variable instance of your sound from the library:
var sndBGMusic:bg_music;

And an instance of the SoundChannel class so you can hear the sound or music.
var sndBGMusicChannel:SoundChannel;

4. Next create an instance of your sound or music with the following:
sndBGMusic=new BGMusic_sound();

Your final actionscript code should look like this:
import flash.media.Sound;
import flash.media.SoundChannel;
var sndBGMusic:bg_music;
var sndBGMusicChannel:SoundChannel;
sndBGMusic=new bg_music();

5. Then simply add the following code to your actionscript when you want the sound or the music to play:
sndBGMusicChannel=sndBGMusic.play();

…simples!


Falkon blog post featured image for post - Flash and HTML5

Flash and HTML5

It's becoming ever rarer to see Flash used as an integral part of websites as a result of the rise...