Search code examples
javascriptflashactionscriptdom-events

Flash, ActionScript, and JavaScript - function not defined


I'm trying to have JavaScript call a function from my ActionScript.

ActionScript:

import flash.external.ExternalInterface;
    
ExternalInterface.addCallback( "playSong", playSong );

function playSong():void {
    var _sound:Sound = new Sound();
    var _request = new URLRequest("music.mp3");
    
    _sound.load(_request);
    _sound.play();
}

JavaScript:

swfobject.embedSWF('http://localhost/music.swf', 'musicplayercontrol1', '1', '1', '9', null, null, { allowScriptAccess: 'always', wmode: 'transparent' }, { }, function( e ) {
    document.getElementById('musicplayercontrol1').playSong();
});

I keep getting a function not defined from Firebug. Anyone know what I'm doing wrong? I tried having the song play as soon as the swf load, and that works for sure.


Solution

  • If you are calling the function directly when the swf is first embeded, the problem could be that the swf is not yet loaded and ready. The function will be undefined until your ActionScript code, including ExternalInterface.addCallback( "playSong", playSong ), is executed. So first the swf must be fully loaded and the ActionScript code executed, before you can call playSong() from JavaScript.