Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ActionScript 2.0 2006

.pdf
Скачиваний:
105
Добавлен:
17.08.2013
Размер:
12.47 Mб
Скачать

Chapter 19

3.Test the SWF by pressing Ctrl+Enter. You should hear your library sound now playing, and it begins at the seconds specified in the start parameter.

How It Works

In this example you created a simple sound object via the new Sound constructor. You left the target parameter of the new Sound constructor blank, so the sound will play independently of any sound objects in other movie clips.

You then used the attachSound method, which specifically targets the library. You passed the attachSound method with a String name of the library ID of the sound file.

Finally, you used the start method to begin playing the sound, passing in a parameter that offset it by 30 seconds to illustrate that you can begin a sound file at an arbitrary position. (If your test sound isn’t very long, try offsetting it by just 3 or 4 seconds.)

Loading External MP3 Files

Loading external MP3 files is as simple as loading library sounds. Instead of using attachMovie, you use loadSound, which uses two parameters. The first targets the URL of the MP3 file, and can be the relative path of a local file if the SWF is running locally. The second parameter determines whether the file should begin playing as soon as enough data exists to play sound, or whether the sound object should wait until the entire sound is loaded before beginning to play the sound. The latter is called an event sound, and there are times when this type of sound is preferred. Event sounds are covered later in this section.

Using ID3 Tags

ID3 tags contain information about the MP3 file being played. The information can contain comments, artist name, track name, and more.

ID3 tags are accessed using the onID3 event in conjunction with polling the id3 property of the sound object. Two types of ID3 tags exist: V2.4 and 1.0. Flash 7 and 8 player supports both, and Flash 6 player supports ID3 1.0 only.

There is a very good reason to upgrade MP3 files that you will use in your SWF to ID3 Version 2. Version 2 tags are available as soon as the MP3 file begins to stream. Version 1 tags are only available at the end of the MP3 file, and so the entire MP3 must load before you can display these tags. So it’s better from a user interface standpoint to make sure your MP3 files utilize the ID3 V2 tags.

You can in fact have both types of tags in your MP3 file. Be aware that the onID3 event will fire when it finds each tag. So if your MP3 file contains two sets of tags, you can expect to be required to handle a second event, and verify the information, or ignore one set of ID3 tags.

If the ID3 tags are not populated within the MP3, the id3 object will return undefined on all tags.

Available Properties in the V2 Tags

Here are descriptions of the available V2 tag properties:

478

 

 

Using ActionScript for Media

 

 

 

 

ID3 PROPERTY

DESCRIPTION

 

 

 

 

TIME

Time

 

TIT1

Content description

 

TIT2

Title, song name, content description

 

TIT3

Subtitle, extended information

 

TFLT

File type

 

TOFN

Filename when the MP3 was created

 

TOLY

Lyricists, text writers

 

TOPE

Artists, performers

 

TORY

Year of release

 

TPE1

Lead performers, singer

 

TPE2

Band, orchestra, accompaniment

 

TPE3

Conductor, performer, extended information

 

TPE4

Remake, Cover, or Remix declaration

 

TPOS

Part of a set

 

TOWN

File owner, licensee, copyright holder

 

TPUB

Publisher

 

TRCK

Track number/position in set

 

TRDA

Recording dates

 

TRSN

Internet radio station name

 

TRSO

Internet radio station owner

 

TOAL

Original album/movie/show title

 

TSIZ

Size

 

TSRC

ISRC (international standard recording code)

 

TSSE

Settings used for encoding

 

TYER

Year

 

WXXX

URL link

 

TKEY

Initial key

 

TLAN

Languages

 

TMED

Media type

 

TLEN

Length

479

Chapter 19

Streaming MP3 Audio

Streaming audio is a useful capability in Flash. Because Flash doesn’t need very much data to play sound, and because of the ubiquity of broadband, you can allow users to begin listening to audio content almost immediately without making them suffer through loading screens and pre-loaders.

Sometimes a file won’t load fast enough, and in those cases Flash may pause playing the audio. When sufficient bytes are received, the audio automatically resumes playing without intervention. Because of this, it’s always wise to monitor the load state of the MP3 file, as well as the current play position.

Starting, Stopping, and Tracking Sound

As good as it is, the sound object is a bit inconstant. For example, the duration and position properties return millisecond positions, but the start method accepts a parameter in seconds, not milliseconds.

When you pause a sound object, you must record the current sound position so that when you call the start method you can resume the sound where you left off. You do this by querying the position property and recording it so that you can insert the value into the start method call when you resume playing. Because of the measurement increment inconsistency, you must divide the milliseconds by 1000 to obtain the seconds value of the current position at which the file should start playing.

To determine the percentage of file played, so that the SWF can display a progress bar, you can divide position by duration to obtain the current percentage of file played. If your progress bar has a maximum width of 200 pixels, you would multiply the percentage played by this width.

Try It Out

Playing and Controlling Sound Objects

For this exercise, you need to place an MP3 file in your work folder. It can be any MP3 file. Use one with known ID3 V2 tags, so you can use it as is. You can add and convert ID3 tags in just about any modern audio player such as Real, iTunes, and Winamp.

1.Open a new FLA and save it as playSound.fla in your work folder.

2.Click the first frame in the timeline, open the Actions panel, and type in the following ActionScript, changing the URL of the MP3 to match the MP3 you are using:

var mySound:Sound = new Sound(); mySound.onID3 = function(){

for(var i in this.id3){ trace(i+”: “+this.id3[i]);

}

}

mySound.loadSound(“myMp3.mp3”, true);

3.Test the code by pressing Ctrl+Enter. You should hear the MP3 now playing. If the MP3 file has Id3 tags, they are now listed in the output panel.

4.Go back and add some controls for your file. You’ll be using component buttons, so open the Components panel and expand the User Interface section.

5.Drag a Button component onto the stage. Place it somewhere near the center of the stage.

480

Using ActionScript for Media

6.Name the instance of this component button playButton in the Properties panel. In the Parameters tab in the Properties panel change the label to Play.

7.Drag another button onto the stage. Place it next to the Play button.

8.Name the instance of this component button stopButton in the Properties panel. In the Parameters tab in the Properties panel change the label to Stop.

9.Drag another button onto the stage. Place it next to the Stop button.

10.Name the instance of this component button rewindButton in the Properties panel. In the Parameters tab in the Properties panel change the label to Rewind. You can align all of the buttons and resize them to suit.

11.Now add a little bit of ActionScript. First, modify the existing code on your timeline with a stop action so that your sound does not start playing by itself. Do this by adding the following line below the existing code:

mySound.stop();

12.Now add actions to the buttons on your stage so you can control the MP3 you just loaded, by entering the following code below the existing code:

var pos:Number = 0; playButton.onRelease = function() {

mySound.start(pos/1000); rewindButton.enabled = true; stopButton.enabled = true; this.enabled = false;

};

playButton.enabled = true; stopButton.onRelease = function() {

pos = mySound.position; mySound.stop(); playButton.enabled = true; this.enabled = false;

};

stopButton.enabled = false; rewindButton.onRelease = function(){

mySound.start(); playButton.enabled = false; stopButton.enabled = true;

}

rewindButton.enabled = false;

13.Add an onSoundComplete event to your sound object so that you can reset the buttons when the sound has stopped playing. Just before the loadSound method, insert the following code:

mySound.onSoundComplete = function(){ pos = 0;

rewindButton.enabled = false;

playButton.enabled = true; stopButton.enabled = false;

}

481

Chapter 19

14.Test the code by pressing Ctrl+Enter. You won’t hear the MP3 playing right away as it did in step 3. Your MP3 is loading in the background. Click the Play button to start the sound playing. Click the Stop and Rewind buttons to make sure they are working.

How It Works

In this example, you saw how, with very little code, to create a functional music player.

You started by constructing a sound object. You then created an onID3 event to check whether the MP3 had information, although you did not display this information in your user interface. You do that in the next Try It Out.

You began to load the sound via the loadSound method, specifying the URL of the MP3 file to play. You also set the sound object type to streaming so that the MP3 file is available to play almost immediately. You’ll want to add some indication of download status to complete this project, and you do that in the next Try It Out.

After you began to load the file, you immediately called the stop method on your sound object. This stopped the sound object from automatically playing on its own. You could remove this to change the default behavior.

You defined your controls with simple onRelease events on each component button you added to the stage.

You also kept an index value called pos, which holds the current position so that when you click Stop, you can store the value for when the start method begins playing the track again. Otherwise, your Play button would always play the song from the beginning of the track.

You also saw that you needed to divide the pos value by 1000 to compensate for the value increment difference between the position property and the start method of the sound object.

Each button was given a toggle to enable and disable it, depending on the current state of the sound object. You used the enabled property of the button component to gray out buttons that can’t be used during different states of the sound object.

Because your buttons have toggles that control their state, and because you are tracking the current position if the user clicks the Stop button, you need to reset the pos value as well as change the button states back to the original non-playing state. You did that by utilizing the onSoundComplete event, which fires as soon as the track has finished playing.

The next bit of code set the Rewind button’s actions, which automatically begins playing the song at the beginning of the track. You called almost the same exact code as you did in the Play button, except the start parameter is set to 0, so the track plays from the very beginning. You could have left this parameter blank because it defaults to 0. However, you might want to change the parameter to something like (pos-10)/1000, which would rewind and play the track 10 seconds before the current position.

482

Using ActionScript for Media

Event Sounds

Event sounds are useful when you need sounds to coincide with interface activity or code functions. Event sounds cannot play until they are fully loaded. Event and streaming sounds both are loaded into the browser cache.

Event sounds and the start method act differently. When you call the start method on a streaming sound, the sound object clears any playing sound within it and starts the track over at the position specified in the parameter of the start method. With event sounds, when you call the start method, the sound is played again, even if it’s already playing. The sound playing from a previous start method call is layered on top, and you hear an echo, or two, or three instances of the sound playing depending on how many times you call start. This can be useful for looping or creating mixers.

Controlling Volume, setPan, and setTransform

You can control some aspects of sound dimensionality. You can control right and left channels, stereo to mono, as well as how much mixing between the two channels occurs. This enables you to make right-to- left specific sound changes that match user interface changes. Of course, games benefit greatly from these properties, but a general user interface can also take advantage of the fun.

Volume

Volume is controlled with two methods: setVolume and getVolume.

Use setVolume when you want to enact a change on the overall volume of the sound object it’s called on. The method accepts an integer from 0 to 100.

getVolume returns the current volume, which is helpful for decreasing or increasing volume using volume fade-in and fade-out techniques. You can also set a volume control in the user interface to match the current volume of the object it’s controlling.

Pan

setPan enables you to move the sound from the left speaker to the right speaker. This is especially useful in games and other situations where spatial effects using sounds are warranted. getPan can be used for algorithms that automatically fade the sounds from left to right. You can also use it to set a user interface control to the current pan position of the object it’s controlling.

Transform

setTransform is a bit more complex, enabling you to mix the left and right channels. You can move a specified amount of sound in the right channel into the left channel fractionally. You can manipulate four properties:

ll — Specifies how much of the left channel of the sound object to play in the left speaker.

lr — Specifies how much of the right channel of the sound object to play in the left speaker.

rr — Specifies how much of the right channel of the sound object to play in the right speaker.

rl — Specifies how much of the left channel of the sound object to play in the right speaker.

483

Chapter 19

setTransform can be highly effective in animation and games that can be enhanced with spatial sound effects using multiple sound objects, each with its own setTransform sound balance. It can help set a user interface control, or initialize a user interface control with the default values. It is also helpful in transferring a sound effect to the same balance. For example, suppose you have a game in which a spaceship has channel-enhanced sound effects for its engines, using setTransform, and you want that spaceship to have a weapons sound effect to match the position of the ship’s engine sound effect. Using the x and y positions of the spaceship, you can automatically set the sound transform matrix for the spaceship, to which all sound effects for that object conform.

These are your sound modification methods. Although trim, they can be a robust set of methods for creating engaging sound effects that excite the user, rather than simply play sound with its original balance.

When you add sound to an application, such as a game or a simple Web form, be aware of how the user might react to the sound, and what the sound relates to visually. A strange or out-of-place sound effect can be jarring and confusing for the user.

Try It Out

Creating a Simple Audio Interface

For this example you’ll want a few MP3 files ready to go. You use the sound object’s methods and properties to create a simple MP3 player with components. Of course, you don’t need to use components, but using them quickly shows you how the sound object behaves. This is a long example; save your FLA often during the instructions so that you do not lose your work.

1.Open a new FLA and save it as musicPlayer.fla in your work folder.

2.Click the first frame in the timeline, open the Actions panel, and type in the following ActionScript. Change the trackPath to match the location of your MP3 files and change the trackListArray to the names of your MP3 files:

trackPath = “tracks/”;

trackListArray = [“song1.mp3”, “song2.mp3”, “song3.mp3”, “song4.mp3”];

3.Expand the User Interface section of the Components panel and drag an instance of the Menu component to the stage. Then delete the stage instance, because the object is now in the library.

4.Go back to the Actions panel and type in the following ActionScript code:

//Create Menu:

var songMenu = mx.controls.Menu.createMenu(); //add each song to the list:

for (var i = 0; i<trackListArray.length; i++) { songMenu.addMenuItem({type:”check”, label:trackListArray[i]});

}

//listen for a selection:

var songSelection = new Object(); songSelection.change = function(event) {

nextTrack(event.menuItem, this);

};

songMenu.addEventListener(“change”, songSelection);

5.Notice the code you just wrote queries the function nextTrack. You create this function by adding the following ActionScript code:

484

Using ActionScript for Media

nextTrack = function (item, obj) { loadSoundFile(trackPath+item.attributes.label); songMenu.setMenuItemSelected(obj.lastSelected, false); songMenu.setMenuItemSelected(item, true); obj.lastSelected = item;

obj.currentIndex = songMenu.indexOf(item);

};

6.Expand the User Interface section of the Components panel and drag an instance of the numericStepper component to the stage. Place it where you want; you’ll be organizing the interface when you have more components on the screen.

7.Select the numericStepper component you just added to the stage and change the height to 22 and the width to 48 in the Properties panel. Give the component an instance name of myVolume. In the Parameters tab, change the maximum value to 100 and the minimum to 0. Be sure the stepSize is 1. You can make the default value 100.

8.Add some ActionScript to work with the numericStepper you just added to the stage by adding the following code below the code you entered in step 5:

//Add Volume control vol = new Object(); //Listen for a change:

vol.change = function(eventObj) { mySound.setVolume(eventObj.target.value);

};

myVolume.addEventListener(“change”, vol);

9.You can see the numericStepper component calls an object called mySound. This is a sound object. Add a function that creates and defines this sound object by typing the following code below the code you entered in step 8:

//Create Sound Object initSound = function () {

mySound = new Sound(); mySound.onID3 = function() {

for (var i in this.id3) { if (i == “artist”) {

var artist:String = this.id3[i]; } else if (i == “songname”) {

var songName:String = this.id3[i];

}

}

trackInfo.text = artist+” <b>>></b> “+songName;

};

mySound.onSoundComplete = function() { rewindButton.enabled = false; playButton.enabled = true; stopButton.enabled = false; clearInterval(progressWatch);

if (songSelection.currentIndex == trackListArray.length-1) { songSelection.currentIndex = 0;

} else { songSelection.currentIndex++;

}

485

Chapter 19

trace(songSelection.currentIndex);

var item = songMenu.getMenuItemAt(songSelection.currentIndex); nextTrack(item, songSelection);

};

};

initSound();

10.The code you just added accesses many objects you haven’t defined yet. Start adding them to the stage now. Expand the User Interface section of the Components panel and drag an instance of the ProgressBar component to the bottom left of the stage. Select the component and give it an instance name of loadStatus.

11.Go back to the ActionScript you’ve been working on and add the following code:

loadStatus.mode = “manual”; loadProgress = function () {

loadStatus.setProgress(mySound.getBytesLoaded(), mySound.getBytesTotal()); if (loadStatus.percentComplete == 100) {

clearInterval(loadWatch);

}

};:

12.Now you need to create a function that will load the sound. You could call your sound object directly, but you want more than one way to load sounds. Because you’ll be loading sounds automatically as tracks are finished, and via user interaction, you can create one function to handle both by adding the following ActionScript to the existing ActionScript in frame 1:

function loadSoundFile(fileURL) { initSound();

loadWatch = setInterval(this, “loadProgress”, 10);

mySound.loadSound(fileURL, true); playButton.onRelease();

}

13.Expand the User Interface section of the Components panel and drag an instance of the ProgressBar component to the top left of the stage. Select the component and give it an instance name of soundIndex. Change the width of the component to 350. Also, you won’t need the text. In the Parameters tab, make the label value blank.

14.Add some ActionScript to your existing ActionScript in frame 1 to control the soundIndex component:

soundIndex.mode = “manual”; progress = function () {

soundIndex.setProgress(mySound.position, mySound.duration);

};

15.Now add a place to display track information. In step 9, you wrote some code that defined the onID3 event of your sound object. Within that function it calls for a text field named trackInfo to accept text. Expand the User Interface section of the Components panel and drag an instance of the TextArea component directly beneath the soundIndex ProgressBar component.

486

Using ActionScript for Media

16.In the Properties panel for the TextArea component, change the name to trackInfo. Change the height of the component to 30. Change the width to 350. In the Parameters tab, be sure the html value is true. In the Parameters tab change the text value to Select a track!.

17.Remember the menu you created in step 4? Add a button to show and hide it now. Expand the User Interface section of the Components panel and drag an instance of the Button component to the stage. Place it just underneath the TextArea component you added in step 15. Place it to the far right, so you have room to the left it for more buttons. In the Button component’s Properties panel, rename the button to tracksButton. Change the width to 50 and change the height to 22.

18.Tell the trackButton what to control by adding the following code below the existing code in the ActionScript in frame 1:

tracksButton.onRelease = function() {

songMenu.show(this.x + this._width - songMenu._width, this.y+this.height);

};

19.Next, add play, stop, and rewind buttons. Expand the User Interface section of the Components panel and drag three instances of the Button component to the stage. Place them underneath the TextArea component you placed on the stage in step 16. Align them to the left side, placing each side by side.

20.Working with the component buttons you just added, select the left button. In the Properties panel, change the name to playButton. Change the height to 22 and the width to 50. In the Parameters tab, change the label to Play.

21.Now select the middle button and, in the Properties panel, change the name to stopButton. Change the height to 22 and the width to 50. In the Parameters tab, change the label to Stop.

22.Now select the button on the right. In the Properties panel, change the name to rewindButton. Change the height to 22 and the width to 75. In the Parameters tab, change the label to Rewind.

23.Move the UI elements on the stage to suit. Organize the user interface so that the controls appear logical and in place. Now add some code to tell your buttons what to do when they are clicked, as well as how to behave when the application loads by adding the following Action Script to frame 1 below your existing code:

playButton.onRelease = function() { mySound.start(pos/1000); rewindButton.enabled = true; stopButton.enabled = true; this.enabled = false;

progressWatch = setInterval(_root, “progress”, 10); mySound.setVolume(myVolume.value);

};

playButton.enabled = false; stopButton.onRelease = function() {

pos = mySound.position; mySound.stop(); playButton.enabled = true; this.enabled = false; clearInterval(progressWatch);

};

stopButton.enabled = false;

487