What is Software? | What is Education? | What is Technology? | What is Research? | What is Wi-Fi? | What is Communication? | What is Customer Service?

Free SEO Tutorials & Help

Tutorials:   Adobe Flash   Adobe Photoshop   CorelDRAW   SEO  

Site Map

Website Development | Cable & Broadband Magazine | Solutions for Higher Education | Auction Anything Online

Adobe Flash Help & Tutorials

 Back to Topics

 

How to Work with Images, Sound, and Video in Flash

Working with Images, Sound, and Video

About loading and working with external media

Loading external SWF and image files

About loading SWF files and the root timeline

About loading and using external MP3 files

Loading an MP3 file

Preloading MP3 files

Reading ID3 tags in MP3 files

Assigning linkage to assets in the library

About using FLV video

Creating a video object

Playing back external FLV files dynamically

Creating a video banner

Preloading FLV files

Working with cue points

Adding seek functionality with cue points (Flash Professional only)

Working with metadata

About configuring FLV files for hosting on a server

About targeting local FLV files on Macintosh

About creating progress animations for media files

Creating a progress animation for loading SWF and image files

Creating a progress bar for loading MP3 files with ActionScript

Creating a progress bar for loading FLV files with ActionScript

Working with Images, Sound, and Video

TOP

If you import an image or a sound while you author a document in Macromedia Flash Basic 8 or Macromedia Flash Professional 8, the image and sound are packaged and stored in a SWF file when you publish it. In addition to importing media while authoring, you can load external media, including other SWF files, at runtime. You might want to keep media outside of a Flash document for several reasons.

Reduce file size By keeping large media files outside of your Flash document and loading them at runtime, you can reduce the initial downloading time for your applications and presentations, especially over slow Internet connections.

Modularize large presentations You can divide a large presentation or application into separate SWF files and load those separate files as needed at runtime. This process reduces initial downloading time and also makes it easier to maintain and update the presentation.

Separate content from presentation This theme is common in application development, especially data-driven applications. For example, a shopping cart application might display an image of each product. By loading each image at runtime, you can easily update a product's image without modifying the original FLA file.

Take advantage of runtime-only features Some features, such as dynamically loaded Flash Video (FLV) and MP3 playback, are available only at runtime through ActionScript.

This section describes how to work with image files, sound files, and FLV video in your Flash applications. For more information, see the following topics:

 

About loading and working with external media

TOP

You can load several types of media files into a Flash application at runtime: SWF, MP3, JPEG, GIF, PNG, and FLV files. However, not all versions of Flash Player support each kind of media. For more information on the image file types that are supported in Macromedia Flash Player 8, see Loading external SWF and image files. For information on FLV video support in Flash Player, see About using FLV video

Adobe Flash Player can load external media from any HTTP or FTP address, from a local disk using a relative path, or by using the file:// protocol.

To load external SWF and image files, you can use the loadMovie() or loadMovieNum() function, the MovieClip.loadMovie() method, or the MovieClipLoader.loadClip() method. The class methods generally provide more function and flexibility than global functions and are appropriate for more complex applications. When you load a SWF or image file, you specify a movie clip or SWF file level as the target for that media. For more information on loading SWF and image files, see Loading external SWF and image files.

To play back an external MP3 file, use the loadSound() method of the Sound class. This method lets you specify whether the MP3 file should progressively download or complete downloading before it starts to play. You can also read the ID3 information embedded in MP3 files, if they're available. For more information, see Reading ID3 tags in MP3 files.

Flash Video is the native video format used by Flash Player. You can play FLV files over HTTP or from a local file system. Playing external FLV files provides several advantages over embedding video in a Flash document, such as better performance and memory management as well as independent video and Flash frame rates. For more information, see Playing back external FLV files dynamically.

You can also preload or track the downloading progress of external media. Flash Player 7 introduced the MovieClipLoader class, which you can use to track the downloading progress of SWF or image files. To preload MP3 and FLV files, you can use the getBytesLoaded() method of the Sound class and the bytesLoaded property of the NetStream class. For more information, see Preloading FLV files.

 

Loading external SWF and image files

TOP

To load a SWF or image file, use the loadMovie() or loadMovieNum() global function, the loadMovie() method of the MovieClip class, or the loadClip() method of the MovieClipLoader class.

For more information on the loadClip() method, see MovieClipLoader.loadClip() in the ActionScript 2.0 Language Reference.

For image files, Flash Player 8 supports the JPEG (progressive and non-progressive) image file type, GIF images (transparent and non-transparent, although only the first frame of an animated GIF will be loaded), and PNG files (transparent and non-transparent).

To load a SWF or image file into a level in Flash Player, use the loadMovieNum() function. To load a SWF or image file into a movie clip target, use the loadMovie() function or method. In either case, the loaded content replaces the content of the specified level or target movie clip.

When you load a SWF or image file into a movie clip target, the upper-left corner of the SWF file or image is placed on the registration point of the movie clip. Because this registration point is often the center of the movie clip, the loaded content might not appear centered. Also, when you load a SWF file or image to a root timeline, the upper-left corner of the image is placed on the upper-left corner of the Stage. The loaded content inherits rotation and scaling from the movie clip, but the original content of the movie clip is removed.

You can optionally send ActionScript variables with a loadMovie() or loadMovieNum() call. This is useful, for example, if the URL you're specifying in the method call is a server-side script that returns a SWF or image file according to data passed from the Flash application.

When you use the global loadMovie() or loadMovieNum() function, specify the target level or clip as a parameter. The following example loads the Flash application contents.swf into the movie clip instance named image_mc:

loadMovie("contents.swf", image_mc);

You can use MovieClip.loadMovie() to achieve the same result:

image_mc.loadMovie("contents.swf");

The following example loads the image1.jpg JPEG image into the image_mc movie clip instance:

image_mc.loadMovie("http://www.helpexamples.com/flash/images/image1.jpg");

For more information about loading external SWF and image files, see About loading SWF files and the root timeline.

To preload SWF and JPEG files into movie clip instances, you can use the MovieClipLoader class. This class provides an event listener mechanism to give notification about the status of file downloads into movie clips. To use a MovieClipLoader object to preload SWF and JPEG files, you must complete the following:

Create a new MovieClipLoader object You can use a single MovieClipLoader object to track the downloading progress of multiple files or create a separate object for each file's progress. Create a new movie clip, load your contents into it, then create the MovieClipLoader object as shown in the following code:

this.createEmptyMovieClip("img_mc", 999);

var my_mcl:MovieClipLoader = new MovieClipLoader();

Create a listener object and create event handlers The listener object can be any ActionScript object, such as a generic Object object, a movie clip, or a custom component.

The following example creates a generic listener object named loadListener and defines for itself onLoadError, onLoadStart, onLoadProgress, and onLoadComplete functions:

// Create listener object:

var mclListener:Object = new Object();

mclListener.onLoadError = function(target_mc:MovieClip, errorCode:String, status:Number) {

trace("Error loading image: " + errorCode + " [" + status + "]");

};

mclListener.onLoadStart = function(target_mc:MovieClip):Void {

trace("onLoadStart: " + target_mc);

};

mclListener.onLoadProgress = function(target_mc:MovieClip, numBytesLoaded:Number, numBytesTotal:Number):Void {

var numPercentLoaded:Number = numBytesLoaded / numBytesTotal * 100;

trace("onLoadProgress: " + target_mc + " is " + numPercentLoaded + "% loaded");

};

mclListener.onLoadComplete = function(target_mc:MovieClip, status:Number):Void {

trace("onLoadComplete: " + target_mc);

};

NOTE : Flash Player 8 allows you to check the HTTP status of a MovieClipLoader download within the onLoadComplete and onLoadError event listeners. This ability allows you to check why the file was unable to download--whether it was a server error, or the file was unable to be found, and so on.

Register the listener object with the MovieClipLoader object In order for the listener object to receive the loading events, you must register it with the MovieClipLoader object, as shown in the following code:

my_mcl.addListener(mclListener);

Begin loading the file (image or SWF) into a target clip To start downloading an image or SWF file, you use the MovieClipLoader.loadClip() method, as shown in the following code:

my_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

NOTE : You can use MovieClipLoader methods only to track the downloading progress of files loaded with the MovieClipLoader.loadClip() method. You cannot use the loadMovie() function or MovieClip.loadMovie() method.

The following example uses the setProgress() method of the ProgressBar component to display the downloading progress of a SWF file. (See ProgressBar.setProgress() in Components Language Reference.)

  1. To display downloading progress by using the ProgressBar component:

  2. Create a new Flash document, and save it as progress.fla.

  3. Open the Components panel (Window > Components).

  4. Drag a ProgressBar component from the Components panel to the Stage.

  5. In the Property inspector (Window > Properties > Properties), name the ProgressBar component my_pb.

  6. Select Frame 1 in the Timeline, and open the Actions panel (Window > Actions).

    Add the following code to the Actions panel:

    var my_pb:mx.controls.ProgressBar;

    my_pb.mode = "manual";

    this.createEmptyMovieClip("img_mc", 999);

    var my_mcl:MovieClipLoader = new MovieClipLoader();

    var mclListener:Object = new Object();

    mclListener.onLoadStart = function(target_mc:MovieClip):Void {

    my_pb.label = "loading: " + target_mc._name;

    };

    mclListener.onLoadProgress = function(target_mc:MovieClip, numBytesLoaded:Number, numBytesTotal:Number):Void {

    var pctLoaded:Number = Math.ceil(100 * (numBytesLoaded / numBytesTotal));

    my_pb.setProgress(numBytesLoaded, numBytesTotal);

    };

    my_mcl.addListener(mclListener);

    my_mcl.loadClip("http://www.helpexamples.com/flash/images/image1.jpg", img_mc);

  7. Test the document by selecting Control > Test Movie.

    The image loads into the movie img_mc clip.

  8. Select File > Publish > Formats, and make sure the SWF and HTML options are selected.

  9. Click Publish and find the HTML and SWF files on your hard disk.

    They're in the same folder as progress.fla that you saved in step 1.

  10. Double-click the HTML document to open it in a browser and see the progress bar animate.

NOTE : When you load files in the test environment, make sure you load an uncached file from the Internet and not a local file if you want to see the progress bar work. A local file loads too quickly to see the progress. Alternatively, upload your SWF file and test your document on a server.

 

About loading SWF files and the root timeline

TOP

The ActionScript property, _root, specifies or returns a reference to the root timeline of a SWF file. If you load a SWF file into a movie clip in another SWF file, any references to _root in the loaded SWF file resolve to the root timeline in the host SWF file, not to that of the loaded SWF file. This action can sometimes cause unexpected behavior at runtime (for example, if the host SWF file and the loaded SWF file both use _root to specify a variable).

In Flash Player 7 and later, you can use the _lockroot (MovieClip._lockroot property) property to force references to _root made by a movie clip to resolve to its own timeline rather than to the timeline of the SWF file that contains that movie clip. For more information, see Specifying a root timeline for loaded SWF files. For more information about using _root and _lockroot, see Best Practices and Coding Conventions for ActionScript 2.0.

One SWF file can load another SWF file from any location on the Internet. However, for a SWF file to access data (variables, methods, and so forth) defined in another SWF file, the two files must originate from the same domain. In Flash Player 7 and later, cross-domain scripting is prohibited unless the loaded SWF file specifies otherwise by calling

System.security.allowDomain().
 

About loading and using external MP3 files

TOP

To load MP3 files at runtime, use the loadSound() method of the Sound class. First, you create a Sound object, as shown in the following example:

var song1_sound:Sound = new Sound();

Use the new object to call loadSound() to load an event or a streaming sound. Event sounds are loaded completely before being played; streaming sounds play as they download. You can set the isStreaming parameter of loadSound() to specify a sound as a streaming or event sound. After you load an event sound, you must call the start() method of the Sound class to make the sound play. Streaming sounds begin playing when sufficient data is loaded into the SWF file; you don't need to use start().

For example, the following code creates a Sound object named my_sound and then loads an MP3 file named song1.mp3. Put the following ActionScript in Frame 1 on the Timeline:

var my_sound:Sound = new Sound();

my_sound.loadSound("http://www.helpexamples.com/flash/sound/song1.mp3", true);

In most cases, set the isStreaming parameter to true, especially if you're loading large sound files that should start playing as soon as possible--for example, when creating an MP3 "jukebox" application. However, if you download shorter sound clips and need to play them at a specified time (for example, when a user clicks a button), set isStreaming to false.

To determine when a sound IS completely downloaded, use the Sound.onLoad event handler. This event handler automatically receives a Boolean value (true or false) that indicates whether the file downloaded successfully.

 

Loading an MP3 file 

TOP

suppose you're creating an online game that uses different sounds that depend on what level the user has reached in the game. The following code loads an MP3 file (song2.mp3) into the game_sound Sound object and plays the sound when it IS completely downloaded.

To load an MP3 file:

  1. Create a new FLA file called loadMP3.fla.

  2. Select Frame 1 on the Timeline, and then type the following code in the Actions panel:

    var game_sound:Sound = new Sound();

    game_sound.onLoad = function(success:Boolean):Void {

    if (success) {

    trace("Sound Loaded");

    game_sound.start();

    }

    };

    game_sound.loadSound("http://www.helpexamples.com/flash/sound/song2.mp3" false);'

  3. Select Control > Test Movie to test the sound.

Flash Player supports only the MP3 sound file type for loading sound files at runtime.
 

Preloading MP3 files 

TOP

When you preload MP3 files, you can use the setInterval() function to create a polling mechanism that checks the bytes loaded for a Sound or NetStream object at predetermined intervals. To track the downloading progress of MP3 files, use the Sound.getBytesLoaded() and Sound.getBytesTotal() methods.

The following example uses setInterval() to check the bytes loaded for a Sound object at predetermined intervals.

To preload an MP3 file:

  1. Create a new FLA file called preloadMP3.fla.

  2. Select Frame 1 on the Timeline and type the following code in the Actions panel:

    // Create a new Sound object to play the sound.

    var songTrack:Sound = new Sound();

    // Create the polling function that tracks download progress.

    // This is the function that is "polled." It checks

    // the downloading progress of the Sound object passed as a reference.

    function checkProgress (soundObj:Object):Void {

    var numBytesLoaded:Number = soundObj.getBytesLoaded();

    var numBytesTotal:Number = soundObj.getBytesTotal();

    var numPercentLoaded:Number = Math.floor(numBytesLoaded / numBytesTotal * 100);

    if (!isNaN(numPercentLoaded)) {

    trace(numPercentLoaded + "% loaded.");

    }

    };

    // When the file has finished loading, clear the interval polling.

    songTrack.onLoad = function ():Void {

    trace("load complete");

    clearInterval(poll);

    };

    // Load streaming MP3 file and start calling checkProgress(),

    songTrack.loadSound("http://www.helpexamples.com/flash/sound/song1.mp3", true);

    var poll:Number = setInterval(checkProgress, 100, songTrack);

  3. Select Control > Test Movie to test the sound.

The Output panel shows loading progress.

You can use the polling technique to preload external FLV files. To get the total bytes and current number of bytes loaded for an FLV file, use the NetStream.bytesLoaded and NetStream.bytesTotal properties (for more information, see bytesLoaded (NetStream.bytesLoaded property) and bytesTotal (NetStream.bytesTotal property) ).
 

Reading ID3 tags in MP3 files 

TOP

ID3 tags are data fields that are added to an MP3 file. ID3 tags contain information about the file, such as the name of a song, album, and artist.

To read ID3 tags from an MP3 file, use the Sound.id3 property, whose properties correspond to the names of ID3 tags included in the MP3 file that you load. To determine when ID3 tags for a downloading MP3 file are available, use the Sound.onID3 event handler. Flash Player 7 supports version 1.0, 1.1, 2.3, and 2.4 tags; version 2.2 tags are not supported.

The following example loads an MP3 file named song1.mp3 into the song_sound Sound object. When the ID3 tags for the file are available, the display_txt text field shows the artist name and song name.

To read ID3 tags from an MP3 file:

  1. Create a new FLA file called id3.fla.

  2. Select Frame 1 on the Timeline and type the following code in the Actions panel:

    this.createTextField("display_txt", this.getNextHighestDepth(), 0, 0, 100, 100);

    display_txt.autoSize = "left";

    display_txt.multiline = true;

    var song_sound:Sound = new Sound();

    song_sound.onLoad = function() {

    song_sound.start();

    };

    song_sound.onID3 = function():Void {

    display_txt.text += "Artist:\t" + song_sound.id3.artist + "\n";

    display_txt.text += "Song:\t" + song_sound.id3.songname + "\n";
    };

    song_sound.loadSound("http://www.helpexamples.com/flash/sound/song1.mp3");]

  3. Select Control > Test Movie to test the sound.

The ID3 tags appear on the Stage, and the sound plays.

Because ID3 2.0 tags are located at the beginning of an MP3 file (before the sound data), they are available as soon as the file starts downloading. ID3 1.0 tags, however, are located at the end of the file (after the sound data), so they aren't available until the entire MP3 file finishes downloading.

The onID3 event handler is called each time new ID3 data is available. So, if an MP3 file contains ID3 2.0 tags and ID3 1.0 tags, the onID3 handler is called twice because the tags are located in different parts of the file.

For a list of supported ID3 tags, see id3 (Sound.id3 property) in the ActionScript 2.0 Language Reference.
 

Assigning linkage to assets in the library

TOP

 
You can assign linkage identifiers for assets in the library, such as movie clips and font symbols. In Flash Basic 8 and Flash Professional 8, you can set linkage identifiers to sound and image assets in the library. This supports using image and sound files with shared libraries and with the new BitmapData class.

The following example adds a bitmap image in the library with a linkage set to myImage. Then you add the image to the Stage and make it draggable.

To use linkage with bitmap files:

  1. Create a new FLA file called linkBitmap.fla.
  2. Import a bitmap image to the library.
  3. Right-click (Windows) or Control-click (Macintosh) the image in the library, and select Linkage from the context menu.
  4. Select Export for ActionScript and Export in first Frame and type myImage in the Identifier text box.
  5. Click OK to set the linkage identifier.
  6. Select Frame 1 on the Timeline, and type the following code in the Actions panel:

    import flash.display.BitmapData;

    // Create imageBmp and attach the bitmap from the library.

    var imageBmp:BitmapData = BitmapData.loadBitmap("myImage");

    // create movie clip and attach imageBmp

    this.createEmptyMovieClip("imageClip", 10);

    imageClip.attachBitmap(imageBmp, 2);

    // make the clip draggable

    imageClip.onPress = function() {

    this.startDrag();

    };

    imageClip.onRelease = function() {

    this.stopDrag();

    }

  7. Select Control > Test Movie to test the document.

The bitmap in the library appears on the Stage, and the image is draggable.

 

About using FLV video

TOP

The FLV file format contains encoded audio and video data for delivery by using Flash Player. For example, if you have a QuickTime or Windows Media video file, you use an encoder (such as Flash 8 Video Encoder, or Sorensen Squeeze) to convert that file to an FLV file.

Flash Player 7 supports FLV files that are encoded with the Sorenson Spark video codec. Flash Player 8 supports FLV files encoded with Sorenson Spark or On2 VP6 encoder in Flash Professional 8. The On2 VP6 video codec supports an alpha channel. Different Flash Player versions support FLV in different ways. For more information, see the following table:

Codec

SWF file version (publish version)

Flash Player version required for playback

Sorenson Spark

6

6, 7, or 8

7

7, 8

On2 VP6

6

8*

7

8

8

8


*If your SWF file loads an FLV file, you can use the On2 VP6 video with having to republish your SWF file for Flash Player 8, as long as users use Flash Player 8 to view your SWF file. Only Flash Player 8 supports publish and playback of On2 VP6 video.

For information on video fundamentals, such as streaming, progressive download, dimensions, encoding, importing, and bandwidth concerns, see Working with Video in Using Flash.

This section discusses using FLV video without components. You can also use the FLVPlayback component to play FLV files or use the VideoPlayback class to create a custom video player that loads FLV files dynamically (see www.macromedia.com/devnet or www.macromedia.com/support/documentation/). For information on using FLV video with the FLVPlayback and Media components, see the following sections:

  • FLVPlayback Component (Flash Professional Only)

  • Media components (Flash Professional only)

As an alternative to importing video directly into the Flash authoring environment, you can use ActionScript to dynamically play external FLV files in Flash Player. You can play FLV files from an HTTP address or from a local file system. To play FLV files, use the NetConnection and NetStream classes and the attachVideo() method of the Video class. For more information, see NetConnection, NetStream, and attachVideo (Video.attachVideo method) in the ActionScript 2.0 Language Reference.

You can create FLV files by importing video into the Flash authoring tool and exporting it as an FLV file. If you have Flash Professional 8, you can use the FLV Export plug-in to export FLV files from supported video-editing applications.

Using external FLV files provides certain capabilities that are not available when you use imported video:

  • Longer video clips can be used in your Flash documents without slowing down playback. External FLV files play using cached memory, which means that large files are stored in small pieces and accessed dynamically, requiring less memory than embedded video files.

  • An external FLV file can have a different frame rate than the Flash document in which it plays. For example, you can set the Flash document frame rate to 30 frames per second (fps) and the video frame rate to 21 fps. This setting gives you better control of the video than embedded video, to ensure smooth video playback. It also allows you to play FLV files at different frame rates without the need to alter existing Flash content.

  • With external FLV files, Flash document playback does not have to be interrupted while the video file is loading. Imported video files can sometimes interrupt document playback to perform certain functions, such as accessing a CD-ROM drive. FLV files can perform functions independently of the Flash document, which does not interrupt playback.

  • Captioning video content is easier with external FLV files because you can use event handlers to access metadata for the video.

TIP : To load FLV files from a web server, you might need to register the file extension and MIME type with your web server; check your web server documentation. The MIME type for FLV files is video/x-flv. For more information, see About configuring FLV files for hosting on a server.
 

 

Creating a video object

TOP

Before you can load and manipulate video using ActionScript, you need to create a video object, drag it to the Stage, and give it an instance name. The following example describes how to add a video instance to an application.

To create a video object:

  1. With a document open in the Flash authoring tool, select New Video from the pop-up menu in the Library panel (Window > Library).

  2. In the Video Properties dialog box, name the video symbol and select Video (ActionScript controlled).

  3. Click OK to create a video object.

  4. Drag the video object from the Library panel to the Stage to create a video object instance.

  5. With the video object selected on the Stage, type my_video in the Instance Name text box in the Property inspector (Window > Properties > Properties).

Now you have a video instance on the Stage, for which you can add ActionScript to load video or manipulate the instance in a variety of ways.

 

Playing back external FLV files dynamically

TOP

You can load FLV files at runtime to play in a SWF file. You can load them into a video object or into a component such as the FLVPlayback component. The following example shows how to play back a file named clouds.flv in a video object.

To play back an external FLV file in a Flash document:

  1. Create a new Flash document called playFLV.fla.

  2. In the Library panel (Window > Library), select New Video from the Library pop-up menu.

  3. In the Video Properties dialog box, name the video symbol and select Video (ActionScript controlled).

  4. Click OK to create a video object.

  5. Drag the video object from the Library panel to the Stage to create a video object instance.

  6. With the video object selected on the Stage, type my_video in the Instance Name text box in the Property inspector (Window > Properties > Properties).

  7. Select Frame 1 in the Timeline, and open the Actions panel (Window > Actions).

  8. Type the following code in the Actions panel:

    this.createTextField("status_txt", 999, 0, 0, 100, 100);

    status_txt.autoSize = "left";

    status_txt.multiline = true;

    // Create a NetConnection object

    var my_nc:NetConnection = new NetConnection();

    // Create a local streaming connection

    my_nc.connect(null);

    // Create a NetStream object and define an onStatus() function

    var my_ns:NetStream = new NetStream(my_nc);

    my_ns.onStatus = function(infoObject:Object):Void {

    status_txt.text += "status (" + this.time + " seconds)\n";

    status_txt.text += "\t Level: " + infoObject.level + "\n";

    status_txt.text += "\t Code: " + infoObject.code + "\n\n";

    };

    // Attach the NetStream video feed to the Video object

    my_video.attachVideo(my_ns);

    // Set the buffer time

    my_ns.setBufferTime(5);

    // Begin playing the FLV file

    my_ns.play("http://www.helpexamples.com/flash/video/clouds.flv");

  9. Select Control > Test Movie to test the document.
     

Creating a video banner

TOP

Video content within banners and other Flash advertisements is often used for advertising, such as showing Flash movie previews or television advertisements. The following example shows how you might create a video instance and add ActionScript in a FLA file to create a banner advertisement that contains video.

To create a video banner:

  1. Create a new Flash document called vidBanner.fla.

  2. Select Modify > Document.

  3. Change the dimensions of your FLA file, type 468 in the width text box and 60 in the height text box.

  4. In the Library panel (Window > Library), select New Video from the Library options.

  5. In the Video Properties dialog box, name the video symbol and select Video (ActionScript controlled).

  6. Click OK to create a video object.

  7. Drag the video object from the Library panel to the Stage to create a video instance.

  8. With the video object selected on the Stage, type my_video in the Instance Name text box in the Property inspector (Window > Properties > Properties).

  9. With the video instance still selected, type 105 in the width text box and 60 in the height text box in the Property inspector.

  10. Drag the video instance to a position on the Stage, or use the Property inspector to set its x and y coordinates.

  11. Select Frame 1 in the Timeline, and open the Actions panel (Window > Actions).

  12. Add the following code to the Actions panel:

    var my_nc:NetConnection = new NetConnection();

    my_nc.connect(null);

    var my_ns:NetStream = new NetStream(my_nc);

    my_video.attachVideo(my_ns);

    my_ns.setBufferTime(5);

    my_ns.play("http://www.helpexamples.com/flash/video/vbanner.flv");

  13. Select Insert > Timeline > Layer to create a new layer, and name it button.

  14. Select the Rectangle tool in the Tools panel.

  15. In the Colors section of the Tools panel, click the pencil icon to select the Stroke color control.

  16. Select No Color, which disables the rectangle's outline.

  17. Drag the pointer diagonally across the Stage to create a rectangle.

    The size of the rectangle does not matter because you'll resize it by using the Property inspector.

  18. Click the Selection tool in the Tools panel then click the rectangle on the Stage to select it.

  19. With the rectangle still selected, type 468 in the width text box and 60 in the height text box in the Property inspector. Then change the X and Y coordinates (X and Y text boxes) to 0.

  20. With the rectangle selected on the Stage, press F8 to change the rectangle into a symbol.

  21. In the Convert to Symbol dialog box, type invisible btn in the Name text box, select Button, and then click OK.

  22. Double-click the new button on the Stage to enter symbol-editing mode.

    The rectangle is currently on the first Up frame of the button you created. This is the Up state of the button--what users see when the button is on the Stage. However, you want the button to not be visible on the Stage, so you need to move the rectangle to the Hit frame, which is the hit area of the button (the active region that a user can click to activate the button's actions).

  23. Click the keyframe at the Up frame, and hold down the mouse button while you drag the keyframe to the Hit frame.

    You can now click in the entire banner area, but there is no visual appearance of the button on your banner.

  24. Click Scene 1 to return to the main Timeline.

    A teal rectangle appears over the banner area, representing the invisible button's hit area.

  25. Select the button you created, open the Property inspector, and type inv_btn in the Instance Name text box.

  26. Select Frame 1 on the Timeline, and then type the following code in the Actions panel:

    inv_btn.onRelease = function(){

    getURL("http://www.macromedia.com");

    };

  27. Make other modifications to the banner, such as adding graphics or text.

  28. Select Control > Test Movie to test the banner in Flash Player.

In this example, you created a banner and resized its dimensions to the established, standardized dimensions that the Interactive Advertising Bureau specifies. For information on standard advertising dimensions (and many other useful guidelines), see the Interactive Advertising Bureau's Standards and Guidelines page at www.iab.net/standards/adunits.asp.

Despite standardized guidelines, ensure that you confirm the advertising guidelines for the advertising service, client, or website that you're advertising with first. If you submit your banner to an advertising company, make sure the file meets a specified file size, dimension, target Flash Player version, and frame-rate guideline. Also, you might have to consider rules about the kinds of media you can use, button code you use in the FLA file, and so on.
 

Preloading FLV files

TOP

To track the downloading progress of FLV files, use the NetStream.bytesLoaded and NetStream.bytesTotal properties. To obtain the total bytes and current number of bytes loaded for an FLV file, use the NetStream.bytesLoaded and NetStream.bytesTotal properties.

The following example uses the bytesLoaded and bytesTotal properties that show the loading progress of video1.flv into the video object instance called my_video. A text field called loaded_txt is dynamically created to show information about the loading progress.

To preload an FLV file:

  1. Create a new FLA file called preloadFLV.fla.

  2. In the Library panel (Window > Library), select New Video from the Library pop-up menu.

  3. In the Video Properties dialog box, name the video symbol and select Video (ActionScript controlled).

  4. Click OK to create a video object.

  5. Drag the video object from the Library panel to the Stage to create a video object instance.

  6. With the video object selected on the Stage, type my_video in the Instance Name text box in the Property inspector (Window > Properties > Properties).

  7. With the video instance still selected, type 320 in the width text box and 213 in the height text box in the Property inspector.

  8. Select Frame 1 in the Timeline, and open the Actions panel (Window > Actions).

  9. Type the following code in the Actions panel:

    var connection_nc:NetConnection = new NetConnection();

    connection_nc.connect(null);

    var stream_ns:NetStream = new NetStream(connection_nc);

    my_video.attachVideo(stream_ns);

    stream_ns.play("http://www.helpexamples.com/flash/video/lights_short.flv");

    this.createTextField("loaded_txt", this.getNextHighestDepth(), 10, 10, 160, 22);

    var loaded_interval:Number = setInterval(checkBytesLoaded, 500, stream_ns);

    function checkBytesLoaded(my_ns:NetStream) {

    var pctLoaded:Number = Math.round(my_ns.bytesLoaded / my_ns.bytesTotal * 100);

    loaded_txt.text = Math.round(my_ns.bytesLoaded / 1000) + " of " + Math.round(my_ns.bytesTotal / 1000) + " KB loaded (" + pctLoaded + "%)";

    progressBar_mc.bar_mc._xscale = pctLoaded;

    if (pctLoaded >= 100) {

    clearInterval(loaded_interval);

    }

    }

  10. Select Control > Test Movie to test your code.

NOTE : If your progress bar loads instantly, the video has cached on your hard disk (either from testing this example or loading it in a different procedure). If this occurs, upload a FLV file to your server and load it instead.
 

Working with cue points

TOP

You can use several different kinds of cue points with Flash Video. You can use ActionScript to interact with cue points that you embed in an FLV file (when you create the FLV file), or that you create by using ActionScript.

Navigation cue points  You embed navigation cue points in the FLV stream and FLV metadata packet when you encode the FLV file. You use navigation cue points to let users seek to a specified part of a file.

Event cue points You embed event cue points in the FLV stream and FLV metadata packet when you encode the FLV file. You can write code to handle the events that are triggered at specified points during FLV playback.

ActionScript cue points External cue points that you create by using ActionScript code. You can write code to trigger these cue points in relation to the video's playback. These cue points are less accurate than embedded cue points (up to a tenth of a second), because the video player tracks them separately.

Navigation cue points create a keyframe at the specified cue point location, so you can use code to move a video player's playhead to that location. You can set particular points in an FLV file where you might want users to seek. For example, your video might have multiple chapters or segments, and you can control the video by embedding navigation cue points in the video file.
If you plan to create an application in which you want users to navigate to a cue point, you should create and embed cue points when you encode the file instead of using ActionScript cue points. You should embed the cue points in the FLV file, because they are more accurate to work with. For more information on encoding FLV files with cue points, see Embedding cue points (Flash Professional only) in Using Flash.

You can access cue point parameters by writing ActionScript. Cue point parameters are a part of the event object received with the cuePoint event (event.info.parameters). For information on accessing or tracing cue points, see Working with cue points in Using Flash.

Tracing cue points from an FLV file

You can trace the cue points that are embedded in an FLV document using NetStream.onMetaData. You need to recurse the structure of the metadata that returns to see the cue point information.

The following code traces cue points in an FLV file:

var connection_nc:NetConnection = new NetConnection();

connection_nc.connect(null);

var stream_ns:NetStream = new NetStream(connection_nc);

stream_ns.onMetaData = function(metaProp:Object) {

trace("The metadata:");

traceMeta(metaProp);

// traceObject(metaProp, 0);

};

my_video.attachVideo(stream_ns);

stream_ns.play("http://www.helpexamples.com/flash/video/cuepoints.flv");

function traceMeta(metaProp:Object):Void {

var p:String;

for (p in metaProp) {

switch (p) {

case "cuePoints" :

trace("cuePoints: ");

//cycles through the cue points

var cuePointArr:Array = metaProp[p];

for (var j:Number = 0; j < cuePointArr.length; j++) {

//cycle through the current cue point parameters

trace("\t cuePoints[" + j + "]:");

var currentCuePoint:Object = metaProp[p][j];

var metaPropPJParams:Object = currentCuePoint.parameters;

trace("\t\t name: " + currentCuePoint.name);

trace("\t\t time: " + currentCuePoint.time);

trace("\t\t type: " + currentCuePoint.type);

if (metaPropPJParams != undefined) {

trace("\t\t parameters:");

traceObject(metaPropPJParams, 4);

}

}

break;

default :

trace(p + ": " + metaProp[p]);

break;

}

}

}

function traceObject(obj:Object, indent:Number):Void {

var indentString:String = "";

for (var j:Number = 0; j < indent; j++) {

indentString += "\t";

}

for (var i:String in obj) {

if (typeof(obj[i]) == "object") {

trace(indentString + " " + i + ": [Object]");

traceObject(obj[i], indent + 1);

} else {

trace(indentString + " " + i + ": " + obj[i]);

}

}

}

 

The following output appears:

The metadata:

canSeekToEnd: true

cuePoints:

cuePoints[0]:

name: point1

time: 0.418

type: navigation

parameters:

lights: beginning

cuePoints[1]:

name: point2

time: 7.748

type: navigation

parameters:

lights: middle

cuePoints[2]:

name: point3

time: 16.02

type: navigation

parameters:

lights: end

audiocodecid: 2

audiodelay: 0.038

audiodatarate: 96

videocodecid: 4

framerate: 15

videodatarate: 400

height: 213

width: 320

duration: 16.334

Using embedded cue points with the FLVPlayback component (Flash Professional only)

You can view cue points for an FLV file in the Property inspector when you use the FLVPlayback component. After you set the contentPath property for the FLVPlayback instance, you can view any cue points that are embedded in the video file. Using the Parameters tab, find the cuePoints property, and click the magnifying glass icon to see a list of the cue points in the file.

NOTE : To see the cue points on the Parameters tab, you must type the name of your FLV file in the contentPath text box instead of using code to assign the contentPath.

The following example shows how to use cue point information with the FLVPlayback component.

To use cue points with the FLVPlayback component:

  1. Create a new Flash document called cueFlv.fla.

  2. Open the Components panel (Window > Components), and drag an instance of the FLVPlayback and TextArea components to the Stage.

  3. Select the TextArea component, and type my_ta in the Instance Name text box in the Property inspector (Window > Properties > Properties).

  4. With the TextArea component still selected, type 200 in the width text box and 100 in the height text box.

  5. Select the FLVPlayback instance on the Stage, and then type my_flvPb in the Instance Name text box.

  6. Select Frame 1 on the Timeline, and type the following code in the Actions panel.

    var my_flvPb:mx.video.FLVPlayback;

    var my_ta:mx.controls.TextArea;

    my_flvPb.contentPath = "http://www.helpexamples.com/flash/video/cuepoints.flv";

    var listenerObject:Object = new Object();

    listenerObject.cuePoint = function(eventObject:Object) {

    my_ta.text += "Elapsed time in seconds: " + my_flvPb.playheadTime + "\n";

    };

    my_flvPb.addEventListener("cuePoint",listenerObject);

  7. Select Control > Test Movie to test the SWF file.

The elapsed time appears in the TextArea instance when the playhead passes each cue point embedded in the document.

Creating cue points with ActionScript to use with components (Flash Professional only)

You can create cue points with ActionScript, and then use them with a video object instance, or one of the video player components (FLVPlayback for Flash Player 8, or MediaPlayback for Flash Player 7). The following examples show you how easy it is to use ActionScript code to create cue points, and then use a script to access them.

NOTE : Embed navigation cue points in a document if you intend to add navigation functionality to an application. For more information, see Working with cue points. For an example of working with embedded cue points, see Using embedded cue points with the FLVPlayback component (Flash Professional only).

To create and use cue points with the FLVPlayback component:

  1. Create a new Flash document called cueFlvPb.fla.

  2. Drag an instance of the FLVPlayback component from the Components panel (Window > Components) to the Stage.

    The component is in the FLVPlayback - Player 8 folder.

  3. Select the component and open the Property inspector (Window > Properties > Properties).

  4. Type my_flvPb in the Instance Name text box.

  5. Drag an instance of the TextArea component from the Components panel to the Stage.

  6. Select the TextArea component and type my_ta in the Instance Name text box.

  7. With the TextArea component still selected, type 200 in the width text box and 100 in the height text box.

  8. Select Frame 1 on the Timeline, and type the following code in the Actions panel:

    var my_flvPb:mx.video.FLVPlayback;

    my_flvPb.contentPath = "http://www.helpexamples.com/flash/video/clouds.flv";
     

    // Create cuePoint object.

    var cuePt:Object = new Object();

    cuePt.time = 1;

    cuePt.name = "elapsed_time";

    cuePt.type = "actionscript";

    // Add AS cue point.

    my_flvPb.addASCuePoint(cuePt);

    // Add another AS cue point.

    my_flvPb.addASCuePoint(2, "elapsed_time2");

    // Display cue point information in text field.

    var listenerObject:Object = new Object();

    listenerObject.cuePoint = function(eventObject) {

    my_ta.text += "Elapsed time in seconds: " + my_flvPb.playheadTime + "\n";

    };

    my_flvPb.addEventListener("cuePoint",listenerObject);

  9. Select Control > Test Movie to test your code.

The following cue points trace in the Output panel:

Elapsed time in seconds: 1.034

Elapsed time in seconds: 2.102

The following example shows how to add cue points at runtime and then trace the cue points when a FLV file plays in the MediaPlayback component.

To create and use cue points with the MediaPlayback component:

  1. Create a new Flash document called cuePointMP.fla

  2. Drag an instance of the MediaPlayback component from the Components panel (Window > Components) to the Stage.

    The component is in the Media - Player 6 - 7 folder.

  3. Select the component, and open the Property inspector (Window > Properties > Properties).\

  4. Type my_mp in the Instance Name text box.

  5. Select the Parameters tab, and click Launch Component Inspector.

  6. In the Component inspector, type http://www.helpexamples.com/flash/video/clouds.flv in the URL text box.

  7. Open the Actions panel (Window > Actions), and type the following code in the Script pane:

    import mx.controls.MediaPlayback;

    var my_mp:MediaPlayback;

    my_mp.autoPlay = false;

    my_mp.addEventListener("cuePoint", doCuePoint);

    my_mp.addCuePoint("one", 1);

    my_mp.addCuePoint("two", 2);

    my_mp.addCuePoint("three", 3);

    my_mp.addCuePoint("four", 4);

    function doCuePoint(eventObj:Object):Void {

    trace(eventObj.type + " = {cuePointName:" + eventObj.cuePointName + " cuePointTime:" + eventObj.cuePointTime + "}");

    }

  8. Select Control > Test Movie to test your code.

The following cue points trace in the Output panel:

cuePoint = {cuePointName:one cuePointTime:1}

cuePoint = {cuePointName:two cuePointTime:2}

cuePoint = {cuePointName:three cuePointTime:3}

cuePoint = {cuePointName:four cuePointTime:4}

 

Adding seek functionality with cue points (Flash Professional only)

TOP

You can embed Navigation cue points in an FLV file to add seeking functionality to your applications. The seekToNavCuePoint() method of the FLVPlayback component locates the cue point in the FLV file with the specified name, at or after the specified time. You can specify a name as a string (such as "part1" or "theParty").

You can also use the seekToNextNavCuePoint() method, which seeks to the next navigation cue point, based on the current playheadTime. You can pass the method a parameter, time, which is the starting time from where to look for the next navigation cue point. The default value is the current playheadTime.

Alternatively, you can also seek to a specified duration of the FLV file, using the seek() method.

In the following examples, you add a button that you use to jump between cue points or a specified duration in a FLV file that plays in the FLVPlayback component, and a button to jump to a specified cue point.

To seek to a specified duration:

  1. Create a new Flash document called seekduration.fla.

  2. Drag an instance of the FLVPlayback component from the Components panel (Window > Components).

    The component is in the FLVPlayback - Player 8 folder.

  3. Select the component and open the Property inspector (Window > Properties > Properties).

  4. Type my_flvPb in the Instance Name text box.

  5. Drag an instance of the Button component from the Components panel to the Stage.

  6. Select the Button component and type my_button in the Instance Name text box.

  7. Select Frame 1 on the Timeline and type the following code in the Actions panel:

    import mx.controls.Button;

    import mx.video.FLVPlayback;

    var seek_button:Button;

    var my_flvPb:FLVPlayback;

    my_flvPb.autoPlay = false;

    my_flvPb.contentPath = "http://www.helpexamples.com/flash/video/sheep.flv";

    seek_button.label = "Seek";

    seek_button.addEventListener("click", seekFlv);

    function seekFlv(eventObj:Object):Void {

    // seek to 2 seconds

    my_flvPb.seek(2);

    }

  8. Select Control > Test Movie to test your code.

When you click the button, the video playhead moves to the duration that you specify: 2 seconds into the video.

To add seeking functionality with the FLVPlayback component:

  1. Create a new Flash document called seek1.fla.

  2. Drag an instance of the FLVPlayback component from the Components panel (Window > Components).

    The component is in the FLVPlayback - Player 8 folder.

  3. Select the component and open the Property inspector (Window > Properties > Properties).

  4. Type my_flvPb in the Instance Name text box.

  5. Drag an instance of the Button component from the Components panel to the Stage.

  6. Select the Button component and type my_button in the Instance Name text box.

  7. Select Frame 1 on the Timeline and type the following code in the Actions panel:

    import mx.video.FLVPlayback;

    var my_flvPb:FLVPlayback;

    my_flvPb.autoPlay = false;

    my_flvPb.contentPath = "http://www.helpexamples.com/flash/video/cuepoints.flv";

    my_button.label = "Next cue point";

    function clickMe(){

    my_flvPb.seekToNextNavCuePoint();

    }

    my_button.addEventListener("click", clickMe);

  8. Select Control > Test Movie to test your code.

The cuepoints.flv file contains three navigation cue points: one each near the beginning, middle, and end of the video file. When you click the button, the FLVPlayback instance seeks to the next cue point until it reaches the last cue point in the video file.

You can also seek to a specified cue point in an FLV file by using the seekToCuePoint() method, as shown in the following example.

To seek to a specified cue point:

  1. Create a new Flash document called seek2.fla.

  2. Drag an instance of the FLVPlayback component from the Components panel (Window > Components).

    The component is in the FLVPlayback - Player 8 folder.

  3. Select the component, and open the Property inspector (Window > Properties > Properties).

  4. Type my_flvPb in the Instance Name text box.

  5. With the FLVPlayback instance still selected, click the Parameters tab.

  6. Type http://www.helpexamples.com/flash/video/cuepoints.flv in the contentPath text box.

    When you type the URL in the contentPath text box, the cue points appear in the Parameters tab (next to cuePoint parameter). Therefore, you can determine the name of the cue point that you want to find in your code. If you click the magnifying glass icon, you can view all of the video file's cue points and information about each cue point in a table.

  7. Drag an instance of the Button component from the Components panel to the Stage.

  8. Select the Button component and type my_button in the Instance Name text box.

  9. Select Frame 1 on the Timeline and type the following code in the Actions panel:

    import mx.video.FLVPlayback;

    var my_flvPb:FLVPlayback;

    my_flvPb.autoPlay = false;

    my_button.label = "Seek to point2";

    function clickMe(){

    my_flvPb.seekToNavCuePoint("point2");

    }

    my_button.addEventListener("click", clickMe);

  10. Select Control > Test Movie to test your code.

The cuepoints.flv file contains three navigation cue points: one each near the beginning, middle, and end of the video file. When you click the button, the FLVPlayback instance seeks to the specified cue point (point2).

 

Working with metadata

TOP

You can use the onMetaData method to view the metadata information in your FLV file. Metadata includes information about your FLV file, such as duration, width, height, and frame rate. The metadata information that is added to your FLV file depends on the software you use to encode your FLV file or the software you use to add metadata information.

NOTE : If your video file does not have metadata information, you can use tools to add metadata information to the file.

To work with NetStream.onMetaData, you must have Flash Video that contains metadata. If you encode FLV files using Flash 8 Video Encoder, your FLV file will have metadata information in it (see the following example for a list of metadata in a FLV file encoded with Flash 8 Video Encoder).

NOTE : Flash Video Exporter 1.2 and later (including Flash 8 Video Exporter), add the metadata to your FLV files. Sorenson Squeeze 4.1 and later also adds metadata to your video files.
The following example uses NetStream.onMetaData to trace the metadata information of an FLV file encoded with Flash 8 Video Encoder.

To use NetStream.onMetaData to view metadata information:

  1. Create a new FLA file called flvMetadata.fla.

  2. In the Library panel (Window > Library), select New Video from the Library pop-up menu.

  3. In the Video Properties dialog box, name the video symbol and select Video (ActionScript controlled).

  4. Click OK to create a video object.

  5. Drag the video object from the Library panel to the Stage to create a video object instance.

  6. With the video object selected on the Stage, type my_video in the Instance Name text box in the Property inspector (Window > Properties > Properties).

  7. With the video instance still selected, type 320 in the width text box and 213 in the height text box.

  8. Select Frame 1 in the Timeline, and open the Actions panel (Window > Actions).

  9. Type the following code in the Actions panel:

    // Create a NetConnection object.

    var netConn:NetConnection = new NetConnection();

    // Create a local streaming connection.

    netConn.connect(null);

    // Create a NetStream object and define an onStatus() function.

    var nStream:NetStream = new NetStream(netConn);

    // Attach the NetStream video feed to the Video object.

    my_video.attachVideo(nStream);

    // Set the buffer time.

    nStream.setBufferTime(30);

    // Being playing the FLV file.

    nStream.play("http://www.helpexamples.com/flash/video/lights_short.flv");

    // Trace the metadata.

    nStream.onMetaData = function(myMeta) {

    for (var i in myMeta) {

    trace(i + ":\t" + myMeta[i])

    }

    };

  10. Select Control > Test Movie to test your code.

You see the following information in the Output panel:

canSeekToEnd: true

audiocodecid: 2

audiodelay: 0.038

audiodatarate: 96

videocodecid: 4

framerate: 15

videodatarate: 400

height: 213

width: 320

duration: 8.04

NOTE : If your video does not have audio, the audio-related metadata information (such as audiodatarate) returns undefined because no audio information is added to the metadata during encoding.

You can also use the following format to display most metadata information. For example, the following code shows the duration of an FLV file:

nStream.onMetaData = function(myMeta) {

trace("FLV duration: " + myMeta.duration + " sec.");

};

This format cannot trace cuePoint metadata information. For information on tracing cue points, see Tracing cue points from an FLV file.
 

About configuring FLV files for hosting on a server

TOP

When you work with FLV files, you might have to configure your server to work with the FLV file format. Multipurpose Internet Mail Extensions (MIME) is a standardized data specification that lets you send non-ASCII files over Internet connections. Web browsers and e-mail clients are configured to interpret numerous MIME types so that they can send and receive video, audio, graphics, and formatted text. To load FLV files from a web server, you might need to register the file extension and MIME type with your web server, so you should check your web server documentation. The MIME type for FLV files is video/x-flv. The full information for the FLV file type is as follows:

Mime Type: video/x-flv

File extension: .flv

Required parameters: none

Optional parameters: none

Encoding considerations: FLV files are binary files; some applications might require the application/octet-stream subtype to be set.

Security issues: none

Published specification: www.macromedia.com/go/flashfileformat.

Microsoft changed the way streaming media is handled in Microsoft Internet Information Services (IIS) 6.0 web server from earlier versions. Earlier versions of IIS do not require any modification to stream Flash Video. In IIS 6.0, the default web server that comes with Windows 2003, the server requires a MIME type to recognize that FLV files are streaming media.

When SWF files that stream external FLV files are placed on a Microsoft Windows 2003 server and are viewed in a browser, the SWF file plays correctly, but the FLV video does not stream.

This issue affects all FLV files placed on Windows 2003 server, including files you make with earlier versions of the Flash authoring tool, the Macromedia Flash Video Kit for Dreamweaver MX 2004. These files work correctly if you test them on other operating systems.
 

About targeting local FLV files on Macintosh

TOP

If you attempt to play a local FLV from a non-system drive on a Macintosh computer by using a path that uses a relative slash (/), the video will not play. Non-system drives include, but are not limited to, CD-ROMs, partitioned hard disks, removable storage media, and connected storage devices.

NOTE : The reason for this failure is a limitation of the operating system, not a limitation in Flash or Flash Player.

For an FLV file to play from a non-system drive on a Macintosh, refer to it with an absolute path using a colon-based notation (:) rather than slash-based notation (/). The following list shows the difference in the two kinds of notation:

Slash-based notation myDrive/myFolder/myFLV.flv

Colon-based notation (Macintosh) myDrive:myFolder:myFLV.flv

You can also create a projector file for a CD-ROM you intend to use for Macintosh playback. For the latest information on Macintosh CD-ROMs and FLV files, see www.macromedia.com/go/3121b301.

 

About creating progress animations for media files

TOP

ActionScript provides several ways to preload or track the downloading progress of external media. You can create progress bars or animations to visually show the loading progress or the amount of content that has loaded.s

To preload SWF and JPEG files, use the MovieClipLoader class, which provides an event listener mechanism for checking downloading progress. For more information, see "Preloading SWF and JPEG files" on page 427.

To track the downloading progress of MP3 files, use the Sound.getBytesLoaded() and Sound.getBytesTotal() methods; to track the downloading progress of FLV files, use the NetStream.bytesLoaded and NetStream.bytesTotal properties. For more information, see "Preloading MP3 files" on page 420.

 

Creating a progress animation for loading SWF and image files

TOP

When you load large SWF or image files into an application, you might want to create an animation that shows the loading progress. You might create a progress bar that shows increases as the animation loads. You might also create an animation that changes as the file loads. For information on loading SWF and image files, see Loading external SWF and image files.

The following example shows how to use the MovieClipLoader class and the Drawing API to show the loading progress of an image file.

To create a progress bar for loading image or SWF files:

  1. Create a new Flash document called loadImage.fla.

  2. Select Modify > Document, and type 700 into the width text box and 500 into the height text box to change the document's dimensions.

  3. Select Frame 1 of the Timeline, and then type the following code in the Actions panel:

    //create clips to hold your content

    this.createEmptyMovieClip("progressBar_mc", 0);

    progressBar_mc.createEmptyMovieClip("bar_mc", 1);

    progressBar_mc.createEmptyMovieClip("stroke_mc", 2);

    //use drawing methods to create a progress bar

    with (progressBar_mc.stroke_mc) {

    lineStyle(0, 0x000000);

    moveTo(0, 0);

    lineTo(100, 0);

    lineTo(100, 10);

    lineTo(0, 10);

    lineTo(0, 0);

    }

    with (progressBar_mc.bar_mc) {

    beginFill(0xFF0000, 100);

    moveTo(0, 0);

    lineTo(100, 0);

    lineTo(100, 10);

    lineTo(0, 10);

    lineTo(0, 0);

    endFill();

    _xscale = 0;

    }

    progressBar_mc._x = 2;

    progressBar_mc._y = 2;

    // load progress

    var mclListener:Object = new Object();

    mclListener.onLoadStart = function(target_mc:MovieClip) {

    progressBar_mc.bar_mc._xscale = 0;

    };

    mclListener.onLoadProgress = function(target_mc:MovieClip, bytesLoaded:Number, bytesTotal:Number) {

    progressBar_mc.bar_mc._xscale = Math.round(bytesLoaded/bytesTotal*100);

    };

    mclListener.onLoadComplete = function(target_mc:MovieClip) {

    progressBar_mc.removeMovieClip();

    };

    mclListener.onLoadInit = function(target_mc:MovieClip) {

    target_mc._height = 500;

    target_mc._width = 700;

    };

    //Create a clip to hold the image.

    this.createEmptyMovieClip("image_mc", 100);

    var image_mcl:MovieClipLoader = new MovieClipLoader();

    image_mcl.addListener(mclListener);

    /* Load the image into the clip.

    You can change the following URL to a SWF or another image file. */

    image_mcl.loadClip("http://www.helpexamples.com/flash/images/gallery1/images/pic3.jpg", image_mc);

  4. Select Control > Test Movie to see the image load and watch the progress bar.

NOTE : If you test this code a second time, the image will be cached and the progress bar will complete right away. To test multiple times, use different images and load them from an external source. A local source might cause problems with testing your application because the content loads too quickly.
 

Creating a progress bar for loading MP3 files with ActionScript

TOP

The following example loads several songs into a SWF file. A progress bar, created using the Drawing API, shows the loading progress. When the music starts and completes loading, information appears in the Output panel. For information on loading MP3 files, see Loading an MP3 file.

  1. To create a progress bar for loading MP3 files:

  2. Create a new Flash document called loadSound.fla.

    Select Frame 1 on the Timeline and type the following code in the Actions panel.

    var pb_height:Number = 10;

    var pb_width:Number = 100;

    var pb:MovieClip = this.createEmptyMovieClip("progressBar_mc", this.getNextHighestDepth());

    pb.createEmptyMovieClip("bar_mc", pb.getNextHighestDepth());

    pb.createEmptyMovieClip("vBar_mc", pb.getNextHighestDepth());

    pb.createEmptyMovieClip("stroke_mc", pb.getNextHighestDepth());

    pb.createTextField("pos_txt", pb.getNextHighestDepth(), 0, pb_height, pb_width, 22);

    pb._x = 100;

    pb._y = 100;

    with (pb.bar_mc) {

    beginFill(0x00FF00);

    moveTo(0, 0);

    lineTo(pb_width, 0);

    lineTo(pb_width, pb_height);

    lineTo(0, pb_height);

    lineTo(0, 0);

    endFill();

    _xscale = 0;

    }

    with (pb.vBar_mc) {

    lineStyle(1, 0x000000);

    moveTo(0, 0);

    lineTo(0, pb_height);

    }

    with (pb.stroke_mc) {

    lineStyle(3, 0x000000);

    moveTo(0, 0);

    lineTo(pb_width, 0);

    lineTo(pb_width, pb_height);

    lineTo(0, pb_height);

    lineTo(0, 0);

    }

    var my_interval:Number;

    var my_sound:Sound = new Sound();

    my_sound.onLoad = function(success:Boolean) {

    if (success) {

    trace("sound loaded");

    }

    };

    my_sound.onSoundComplete = function() {

    clearInterval(my_interval);

    trace("Cleared interval");

    }

    my_sound.loadSound("http://www.helpexamples.com/flash/sound/song2.mp3", true);

    my_interval = setInterval(updateProgressBar, 100, my_sound);

    function updateProgressBar(the_sound:Sound):Void {

    var pos:Number = Math.round(the_sound.position / the_sound.duration * 100);

    pb.bar_mc._xscale = pos;

    pb.vBar_mc._x = pb.bar_mc._width;

    pb.pos_txt.text = pos + "%";

    }

  3. Select Control > Test Movie to load the MP3 file and watch the progress bar.

NOTE : If you test this code a second time, the image will be cached and the progress bar will complete right away. To test multiple times, use different images and load them from an external source. A local source might cause problems with testing your application because the content loads too quickly.

 

Creating a progress bar for loading FLV files with ActionScript

TOP

You can create a progress bar to display the loading progress of an FLV file. For information on loading FLV files into a SWF file, see Preloading FLV files. For other information about FLV files and Flash, see About using FLV video.

The following example uses the Drawing API to create a progress bar. The example also uses the bytesLoaded and bytesTotal properties to show the loading progress of video1.flv into the video object instance called my_video. The loaded_txt text field is dynamically created to show information about the loading progress.

To create a progress bar that shows loading progress:

  1. Create a new FLA file called flvProgress.fla.

  2. In the Library panel (Window > Library), select New Video from the Library pop-up menu.

  3. In the Video Properties dialog box, name the video symbol and select Video (ActionScript controlled).

  4. Click OK to create a video object.

  5. Drag the video object from the Library panel to the Stage to create a video object instance.

  6. With the video object selected on the Stage, type my_video in the Instance Name text box in the Property inspector (Window > Properties > Properties).

  7. With the video instance selected, type 320 into the width text box and 213 into the height text box.

  8. Select Frame 1 in the Timeline and type the following code in the Actions panel:

    var connection_nc:NetConnection = new NetConnection();

    connection_nc.connect(null);

    var stream_ns:NetStream = new NetStream(connection_nc);

    my_video.attachVideo(stream_ns);

    stream_ns.play("http://www.helpexamples.com/flash/video/typing_short.flv");

    this.createTextField("loaded_txt", this.getNextHighestDepth(), 10, 10, 160, 22);

    this.createEmptyMovieClip("progressBar_mc", this.getNextHighestDepth());

    progressBar_mc.createEmptyMovieClip("bar_mc", progressBar_mc.getNextHighestDepth());

    with (progressBar_mc.bar_mc) {

    beginFill(0xFF0000);

    moveTo(0, 0);

    lineTo(100, 0);

    lineTo(100, 10);

    lineTo(0, 10);

    lineTo(0, 0);

    endFill();

    _xscale = 0;

    }

    progressBar_mc.createEmptyMovieClip("stroke_mc", progressBar_mc.getNextHighestDepth());

    with (progressBar_mc.stroke_mc) {

    lineStyle(0, 0x000000);

    moveTo(0, 0);

    lineTo(100, 0);

    lineTo(100, 10);

    lineTo(0, 10);

    lineTo(0, 0);

    }

    var loaded_interval:Number = setInterval(checkBytesLoaded, 500, stream_ns);

    function checkBytesLoaded(my_ns:NetStream) {

    var pctLoaded:Number = Math.round(my_ns.bytesLoaded / my_ns.bytesTotal * 100);

    loaded_txt.text = Math.round(my_ns.bytesLoaded / 1000) + " of " + Math.round(my_ns.bytesTotal / 1000) + " KB loaded (" + pctLoaded + "%)";

    progressBar_mc.bar_mc._xscale = pctLoaded;

    if (pctLoaded>=100) {

    clearInterval(loaded_interval);

    }

    }

  9. Select Control > Test Movie to test your code.

The video loads and an animating bar and changing text values communicate the loading progress. If these elements overlap your video, move the video object on the Stage. You can customize the color of the progress bar by modifying beginFill and lineStyle in previous code snippet.

NOTE : If your progress bar loads instantly, the video is cached on your hard disk (either from testing this example already, or loading it in a different procedure). If this occurs, upload a FLV file to your server and load it instead.
 

Copyright ADOBE - All Rights Reserved Worldwide

 

 

More Topics:

Working with Flash Documents

How to work in Flash WorkSpace

Working with Projects in Flash

Process to Build your First Application in Flash

Using Symbols, Instances and Library Assets in Flash

How to Build Video Player in Flash

How to Work with Color, Strokes and Fills in Flash

How to Create Document in Flash

What is Vector and Bitmap Graphics in Flash

How to Create a Banner in Flash, Part 1

How to Work with Text in Flash

How to Create a Banner in Flash, Part 2

How to Use Imported Artwork in Flash

How to Create a Banner in Flash, Part 3

How to Work with Graphic Objects in Flash

How to Work with Layers in Flash

How to Use Filters and Blends

Working with Graphics in Flash

What is Accessibility Features in Flash

How to Create Motion (Shape Tween & Motion Tween) in Flash

How to Create an Application in Flash

What is Masking in Flash

How to Work with Video in Flash

How to Use Layout Tools in Flash

What are Behaviors in Flash

How to Work with Sound in Flash

How to Create Symbols and Instances in Flash

What is ActionScript in Flash

How to Write ActionScript With Script Assist in Flash

How to Add Button Animation and Navigation in Flash

What is Data Integration in Flash

How to Work with Screens

How to Create a Presentation with Screens

What is Extending Flash

How to Create Multilanguage Text in Flash

How to Create Graphics: Draw in Flash

What is Flash Lite

Ways of Data Integration

How to Create Graphics: Create a Timeline Animation in Flash

Getting Started with Flash Lite in Flash

How to Publish Flash Documents

How to Create Graphics: Making Animations with Easing

Learning Flash Lite 1.X ActionScript in Flash

How to Export Flash Content and Images from Flash

How to Create Graphics: Applying Gradients in Flash

Process of Writing and Editing ActionScript 2.0 in Flash

How to Create Accessible Content in Flash

How to Create Graphics: Apply Graphic Filters and Blends

What is Data and Data Types in Flash

Process of Printing from SWF Files in Flash

Using ActionScript: How to Use Script Assist mode in Flash

Learn Syntax and Language Fundamentals in Flash

How to Create E-learning Content in Flash

Using ActionScript: How to Write Scripts in Flash

Working with Functions and Methods in Flash

Process of Using Templates in Flash

Using ActionScript: Process of Adding Interactivity in Flash

What are Classes in Flash

Control Tag Summary of XML to UI in Flash

Using ActionScript: How to Create a Form with Conditional Logic and Send Data in Flash

What is Inheritance in Flash

What is Data Integration: Overview

Using ActionScript: How to Work with Objects and Classes in Flash

Overview on Interfaces in Flash

What is Data Integration: Using XML for a Timesheet

How to Work with Text and Strings in Flash

How to use Handling Events in Flash

What is Data Integration: Using XUpdate to Update the Timesheet

Learning Animation, Filters and Drawings in Flash

How to Work with Movie Clips in Flash

How to Create Interaction with ActionScript in Flash

How to Work with Images, Sound, and Video in Flash

How to Work with External Data in Flash

What is Security in Flash

How to Debug Applications in Flash

List of Error Messages in Flash

Using Object-Oriented Programming with ActionScript 1.0 in Flash

How to Write Scripts for Earlier Versions of Flash Player in Flash

List of all Keyboard Keys and Key Code Values for using in Flash

Terminology

Introduction to Components in Flash

What are Components in Flash

How to Create an Application with Components

How to Work with Components in Flash

How to Handle Component Events in Flash

How to Customize Components in Flash

How to Create Components in Flash

What is Collection Properties in Flash