Search code examples
actionscript-3flash-cs4

As3, how do I pass a message to all swfs in a page?


Basically I created a simple mp3 player, and there are multiple copies of that embedded in a page. Now when I play one, I want all the others to pause.....any idea how to do this? is it possible to do n-way localconnection? or is there a better alternative?


Solution

  • ExternalInterface.call can be used to call JavaScript from a SWF and, vice-versa, ExternalInterface.addCallback can be used to expose certain methods to be called by JavaScript.

    For example, in each SWF, you might have:

    ExternalInterface.addCallback("externalStopAudio", stopAudio);
    
    // later..
    function stopAudio():void {
        // Code to stop audio
        _audioStream.stop(); 
    }
    
    function playAudio():void {
        // tell JS to stop all audio
        ExternalInterface.call("stopAllAudio");
        // play this players audio
        _audioStream.play();
    }
    

    And then in the JS that is part of the HTML containing the SWF:

    <script>
        // these references need to be actual pointers to the SWFs, this will vary 
        // depending on how you have it setup - might be SWFObject, Jquery, etc
        var a = [swf1, swf2, swf3];
    
        // called by SWF
        function stopAllAudio() {
            // called to SWF
            for(var i = 0; i < a.length; i++) {
                 a[i].externalStopAudio();
            }
        }
    
    </script>
    

    Depending on security settings/domain placement, you may need the following:

    In HTML:

    <param name="allowScriptAccess" value="always" />
    

    In SWF:

    flash.system.Security.allowDomain(sourceDomain)
    

    See: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html#addCallback%28%29