Section 8.3. Scripting Your Own Sound Control


8.3. Scripting Your Own Sound Control

There will undoubtedly be instances when you don't want to rely on components, or you want to script specific features for your sound player. For these reasons, it's a good idea to have at least a minimal understanding of the Sound class, so you can create sound objects and control them with code. Fortunately, it's very easy.

8.3.1. Creating a Sound Object

All you have to do to play an MP3 using your own script is create a sound object, load the sound, and, once the sound is finished loading, play it. This next mini-project starts by doing just that, using the Nero sound you've been working with:

  1. Create a new file and save it as mouse_sound.fla in your 08 folder.

  2. In frame 1, add the following script:

     var my_sound:Sound = new Sound(); my_sound.loadSound("nero.mp3"); my_sound.onLoad = function():Void {     my_sound.start(); }; 

  3. Save your work and test your movie. The sound should begin playing automatically.

That was quick and painless, but there's more you can do with sound than just playing it.

8.3.2. Volume

Controlling the volume of a sound is as easy as setting it to a value from 0 to 100, inclusive:

  1. Continuing with the current movie, add the following line to the end of your frame 1 script:

     my_sound.setVolume(50); 

  2. Save your work and test your movie. The sound should now play at half volume.

Hard-coding a volume like that is useful for an initialization routine but isn't very practical for ongoing use. However, if you could vary the value used for setVolume(), instead of restricting your use to a value of 50, you would be able to change the volume at will. You could, for example, create a volume slider that matched the vertical (or horizontal, if you prefer) position of a slider button movie clip. You'll do just that in a moment, but first you'll look at the pan property.

8.3.3. Pan

The pan property defines what amount of the sound is in each of the left and right channels (for stereo sound). Setting the pan of a sound is as easy as setting the volume, with one wrinkle: you need to be able to specify any pan between all left channel and all right channel. Therefore, a range of 0 to 100 is insufficient.

Instead, the range of a pan is from100 (all left) to 100 (all right), with a value of 0 being equal amounts of sound in both channels. To see how it works, try this:

  1. Continuing with the current movie, add the following line to the end of your frame 1 script:

     my_sound.setPan(100); 

  2. Save your work and test your movie. The sound should now play only in the right channel.

Again, hard-coding a pan value would not be as useful as allowing the user to change the value. If desired, you could take the same approach with pan as discussed in the "Volume" section. You might use a slider with a center point or, more intuitively, a knob that would allow you to use a rotation value.

8.3.4. The Whole Works

Next, you'll create two different projects to see these principles at work. First, you'll create a mouse toy that controls volume and pan with mouse position, and then you'll script a pre-configured interface to make an MP3 player of your own. Both require a bit more ActionScript labor than you've had to do up to this point, but it will be worth it.

8.3.5. Mouse sound

For this project, you'll let the x-coordinate of the mouse control the pan and the y-coordinate of the mouse control the volume. Before you can continue, however, there are two small user interface issues that you'll need to consider.

First, the Flash coordinate system begins with (0, 0) in the upper-left corner of the Stage, and the x and y values increase moving to the right and down. Therefore, a span of y values starts at zero and increases as you move the mouse down. This is not very intuitive for the average user, so you'll use a little math to flip these values, allowing the volume of the sound to start at zero at the bottom of the Stage and increase as you move the mouse up.

Second, if the x values start at 0 on the far left, it will not be very intuitive for the user to get values between 100 and 100 while keeping his or her mouse on the Stage. Thus, you will adjust the _xmouse value to assume a position of zero in the horizontal center of the screen:

  1. Start with almost the same code you've been using, but with one exception. Instead of playing the sound when it's loaded, play it when the user clicks the mouse anywhere in the main timeline. Entirely replace your existing frame 1 script with the following:

     var my_  sound:Sound = new Sound(); my_sound.loadSound("nero.mp3"); this.onMouseDown = function():Void {      my_sound.start(); }; 

  2. Next, make your file run more efficiently by performing two simple calculations and storing them in variables that can be recalled later. This prevents your file from having to repeat these calculations at every enter frame. The first gives you the horizontal center point of the Stage, and the second gives you the height of the Stage:

     var centerStage:Number = Stage.width / 2; var sh:Number = Stage.height; 

  3. Then add an enterFrame event handler for the main timeline with the following code:

     this.onEnterFrame = function():Void {     my_sound.setVolume(Math.abs(100 - (_ymouse / sh) * 100));  }; 

    This code will set the volume of the sound based on how far the mouse has moved up the Stage vertically. Remember that you want a value from 0100 for volume. If you divide _ymouse by the Stage height, you will get a percentage of vertical Stage distance traveled by the mouse. You can then multiply that by 100 to get a value between 0 and 100, rather than between 0 and 1.

    However, that's not all. That will work with the default y value of 0 at the top. Therefore, the values will only increase when moving the mouse down, which is the opposite of what you want. To offset this, you can subtract the value you get from 100. Therefore, where the value at the bottom used to be 100, it is now 0. The problem is, a value of 0 at the top is now negative 100.

    The final step is to take the absolute value of the number you've calculated. This will make a positive number from a positive number or a negative number. The Math class takes care of that for you automatically by simply invoking the built-in Math.abs() method. Now, at last, you will get values from 0 to 100 by moving the mouse up the Stage, vertically.

  4. Add a second and final line to the same enterFrame handler (the new line is indicated in bold):

     this.onEnterFrame = function():Void {      my_sound.setVolume(Math.abs(100 - (_ymouse / sh) * 100));     my_sound.setPan(((_xmouse - centerStage) / centerStage) * 100); }; 

    This line sets the pan based on the horizontal mouse value, or _xmouse. The twist is that it needs to calibrate zero at the center of the Stage. It uses the same method of distance traveled divided by total distance times 100, but it offsets the distance traveled by accounting for the center of the Stage. Therefore, using your 550-pixel-wide Stage as an example, and a mouse value of 0, you get:

    Table 8-1.

    Far left:

    (0 275) / 275 = 1 * 100

    =100

    Center:

    (275 275) / 275 = 0 * 100

    = 0

    Far right:

    (550 275) / 275 = 1 * 100

    = 100


  5. Save your work and test your movie.

You should now be able to move your mouse to the right of center Stage to pan the sound to the right, and to the left of center Stage to pan the sound to the left. Also, your sound should be at full volume at the top of the Stage, and muted at the bottom of the Stage.

8.3.6. MP3 player

This project calls for you to create a basic sound player. The player will include track selection, play, pause, stop, and song loop features; a volume slider; and a pan knob. This is an intermediate project, and the step-by-step walk-through will be just a bit sparser than usual as a challenge to push you forward. Everything you need has been provided, though, so with a bit of effort you should be just fine.

For brevity, the code for the slider and knob will be skipped in the following steps. However, the code is not complicated and uses the basic principles discussed in the " Mouse sound" section. When you feel comfortable with this project, you can double-click on the volume slider and pan knob and look at the code in each to see how they were scripted.


Note: If you plan to use the template file provided, you can disregard this note. However, if you decide to reconstruct the file for yourself at a later time, you should be aware of five things. In the provided source file:

Again, for brevity, you will start with a file that has already been assembled, with instance names applied to the various pieces. However, all of the pieces for your player were taken from a button library that has been a part of Flash for several versions. The assets can be found in the Library spawned by the Window Common Libraries Buttons menu command. Within the opened Library, the buttons can be found in the Playback folder, and the volume slider and pan knob can be found in the Knobs and Here's how to implement your player:

  1. Open the mp3_player_manual_01.fla file in the 08 folder. Remember, the interface elements and instance names are all in place, and the slider and knob have been scripted to work on their own. However, you have to script the sound object and all the buttons. The interface should look like Figure 8-7.

    Figure 8-7. The MP3 player interface

  2. Start by initializing variables and setting the visibility of the loop indicator to false:

     var my_sound:Sound = new Sound(); var whichTrack:String = "GB1.mp3"; var trackNum:Number = 1; var trackPos:Number = 0; var trackLoop:Boolean = false; var trackPlaying:Boolean = false; loopLabel_mc._visible = false; 

  3. Next, define the function used to switch tracks:

     function switchTrack(incr:Number):Void {     trackNum += incr;     if (trackNum > 3) {         trackNum = 1;     } else if (trackNum == 0) {         trackNum = 3;     }     track_mc.value.text = "GB" + trackNum;     whichTrack = track_mc.value.text + ".mp3";     trackPos = 0;     my_sound.loadSound(whichTrack);     my_sound.stop(); } switchTrack(0); 

    This function accepts an integer and returns nothing. When called, the trackNum variable is incremented with 1 or 1, increasing or decreasing the track number. The conditional makes sure that only the numbers 1, 2, and 3 are used. The track name is then assembled ("GB" + 2 + ".mp3," for example), its position is reset to zero, the sound is loaded, and then it's stopped awaiting playback. Finally, the function is called once as an initialization step, loading the first track.

  4. An onSoundComplete event handler is created to restart the sound when it's finished playing. However, this occurs only if the trackLoop variable is true:

     my_sound.onSoundComplete = function():Void {     if (trackLoop) {         my_sound.start(0);     } }; 

  5. Next and previous buttons are scripted to call the function defined earlier. The next button sends a positive increment (1), increasing the track number, while the previous button sends a negative increment (1), decreasing the track number:

     next_btn.onRelease = function():Void {     switchTrack(1); }; prev_btn.onRelease = function():Void {     switchTrack(-1); }; 

  6. If the track is not already playing, the play button starts the sound. However, it accounts for the current position of the sound:

     play_btn.onRelease = function():Void {     if (!trackPlaying) {         trackPlaying = true;             my_sound.start(trackPos / 1000);     } }; 

    The track position is normally zero when the sound is stopped, but the pause feature will record the sound playback position when the pause button is clicked. Starting the sound from that position will cause it to pick up where the pause left off. Note that the sound position property is measured in milliseconds, but the offset parameter of the start method is measured in seconds. Therefore, the position value stored in the pause button must be divided by 1000 to get the right units.

  7. Pause and stop buttons set the trackPlaying variable to false, store the track position in the trackPos variable, and stop the sound:

     pause_btn.onRelease = function():Void {     trackPlaying = false;     trackPos = my_sound.position;     my_sound.stop(); }; stop_btn.onRelease = function():Void {     trackPlaying = false;     trackPos = 0;     my_sound.stop(); }; 

    The only difference between the pause and stop buttons is that the stop button hard-codes a value of zero for track position to reset the sound for subsequent playback from the beginning.

  8. Finally, the loop button turns the looping feature on and off:

     loop_btn.onRelease = function():Void {     trackLoop = !trackLoop;     if (trackLoop) {         loopLabel_mc._visible = true;     } else {         loopLabel_mc._visible = false;     } }; 

    All this button really does is reverse the trackLoop variable. If it was true it is changed to false, and vice versa. This variable is checked when the onSoundComplete handler is called, as seen in step 4. However, as an interface consideration, the loopLabel_mc movie clip that says "LOOP" is shown or hidden, accordingly.

That's it! Not only have you gotten through quite a bit of ActionScript in this chapter, but you're using strict data typing and really making progress. Congratulations.

8.3.7. What's Next?

As you complete each new chapter, you're learning new ActionScript skills. If your confidence is growing, try using some of the other properties and methods of the Sound object before moving on.

For example, try to create a pair of buttons that let you mute and unmute your sounds instantly. Make a mute button that uses getVolume() to store the current volume setting in a variable and then uses setVolume() to set the volume to zero. Then make an unmute button that retrieves the old volume level from the variable you used previously and uses setVolume() again to restore the previous setting.

If you're not yet ready to try this experiment on your own, don't worry. By the time you're finished with this book you'll be able to tackle this task, and more. If you want to see how it could be done, or check your work, look at mute_01.fla in the 08 folder.

In the next chapter, you'll take a similar look at how to add video to your projects, with and without ActionScript. You'll learn how to:

  • Embed video in your SWF files

  • Encode video using the Flash 8 Video Encoder

  • Load external videos using additional media components

  • Script your own video control using ActionScript



Flash 8(c) Projects for Learning Animation and Interactivity
Flash 8: Projects for Learning Animation and Interactivity (OReilly Digital Studio)
ISBN: 0596102232
EAN: 2147483647
Year: 2006
Pages: 117

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net