Как зациклить последовательность загруженных SWF-файлов? - PullRequest
0 голосов
/ 25 апреля 2018

READY! Вот оно: у нас есть простой, но полезный код, который последовательно загружает 2 файла SWF ...

Но как я могу это сделать?

Как изменить код для загрузки swf1 после завершения swf2?

Я пробовал почти целый день , но результата пока нет ... Пожалуйста, помогите ... Даже с вашими комментариями любая любая идея очень ценится.

Большое спасибо ...

Вот код:

import com.greensock.*;
import com.greensock.loading.*;
import com.greensock.events.LoaderEvent;
import flash.events.Event;


//create SWFLoaders


var swf1:SWFLoader = new SWFLoader("child1.swf",{container:this,y:100,onProgress:progressHandler,onComplete:completeHandler,autoPlay:false});
var swf2:SWFLoader = new SWFLoader("child2.swf",{container:this,y:100,onProgress:progressHandler,onComplete:completeHandler,autoPlay:false});
var currentSWFLoader:SWFLoader = swf1;


//adjust the progress bar;
function progressHandler(e:LoaderEvent):void {
    bar.scaleX = e.target.progress;
    trace(e.target.progress);
}


//tell the loaded swf to play and start tracking frames
function completeHandler(e:LoaderEvent):void {
    //the target of the LoaderEvent is the SWFLoader that fired the event
    //the rawContent is the loaded swf
    e.target.rawContent.play();
    addEventListener(Event.ENTER_FRAME, checkFrame);
}


function checkFrame(e:Event):void {
    //check to see if loaded swf is done playing
    if (currentSWFLoader.rawContent.currentFrame == currentSWFLoader.rawContent.totalFrames) {
        trace("swf done playing");
        removeEventListener(Event.ENTER_FRAME, checkFrame);


        //if the first swf is done playing load the second swf
        if (currentSWFLoader == swf1) {
            currentSWFLoader.dispose(true) // dispose and unload content
            currentSWFLoader = swf2;
            currentSWFLoader.load();
        }
    }
}


bar.scaleX = 0;
currentSWFLoader.load();

1 Ответ

0 голосов
/ 25 апреля 2018

Вам нужен ООП подход.

Сначала создайте класс, который полностью обрабатывает один внешний SWF-файл: загрузка, воспроизведение, сигнал об окончании воспроизведения, выгрузка и очистка.

package
{
    // Imports.
    import flash.events.Event;

    import flash.net.URLRequest;

    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.display.MovieClip;

    public class ExternalMovie extends Sprite
    {
        private var L:Loader;
        private var M:MovieClip;

        // Handles loading.
        public function loadAndPlay(url:String):void
        {
            L = new Loader;
            addChild(L);

            L.contentLoaderInfo.addEventListener(Event.INIT, onLoaded);
            L.load(new URLRequest(url));
        }

        // Handles Loader.contentLoaderInfo event Event.INIT.
        private function onLoaded(e:Event):void
        {
            L.contentLoaderInfo.removeEventListener(Event.INIT, onLoaded);

            // Get a direct reference to the loaded movie root.
            M = L.content as MovieClip;

            // Set up the watchdog for loaded movie to finish.
            addEventListener(Event.ENTER_FRAME, onWatch);
        }

        // Event.ENTER_FRAME handler to watch the loaded movie playback.
        private function onWatch(e:Event):void
        {
            if (M.currentFrame >= M.totalFrames)
            {
                M.stop();

                // Announce the end of playback.
                dispatchEvent(new Event(Event.COMPLETE));
            }
        }

        // Unloads movie and cleans up.
        public function dispose():void
        {
            removeEventListener(Event.ENTER_FRAME, onWatch);

            L.unloadAndStop(true);

            removeChild(L);

            L = null;
            M = null;
        }
    }
}

Во-вторых, создайте управляющий скрипт, который создает экземпляр этого класса, велит ему воспроизводить SWF по его URL-адресу, затем ждет окончания воспроизведения и переходит к следующему фильму.

import ExternalMovie;

var EML:ExternalMovie;

var current:int = -1;
var plan:Array = ["child1.swf", "child2.swf"];

// Start the first one manually.
playNext();

function playNext(e:Event = null):void
{
    // Clean up the last one, if any.
    if (EML)
    {
        removeChild(EML);

        EML.removeEventListener(Event.COMPLETE, playNext);
        EML.dispose();
        EML = null;
    }

    // Switch to next url.
    current++;

    // Loop from the beginning if last movie just played.
    if (current >= plan.length)
    {
        current = 0;
    }

    // Get the next movie URL.
    var nextURL:String = plan[current];

    EML = new ExternalMovie;

    // Subscribe to Event.COMPLETE event to know the exact moment the
    // current movie finished playing to remove it and load the next one.
    EML.addEventListener(Event.COMPLETE, playNext);
    EML.loadAndPlay(nextURL);

    addChild(EML);
}

Имейте в виду, что все вышеперечисленное является скорее ориентиром, чем законченным рабочим решением (хотя оно может работать только ).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...