Search code examples
pluginsosmf

Listening to current time change with an OSMF proxy plugin


I am trying to create a proxy plugin for OSMF that will serve as an analytics plugin, that tracks certain events. I want to track the current time of the video.

In the set method for the proxied element, I have the following:

proxiedElement.addEventListener(MediaElementEvent.TRAIT_ADD, _onTraitAdd);

Then, in the _onTraitAdd method, I am attaching event listeners for the DURATION_CHANGE and CURRENT_TIME_CHANGE events.

    private function _onTraitAdd(event:MediaElementEvent ):void {
        trace("adding trait");
        trace(event.traitType);

        if (MediaTraitType.TIME == event.traitType) 
        {
            //Get the time trait, so we can handle the duration changed event
            var timeTrait:TimeTrait = proxiedElement.getTrait( MediaTraitType.TIME ) as TimeTrait;
            timeTrait.addEventListener( TimeEvent.DURATION_CHANGE, _onDurationChanged );
            timeTrait.addEventListener( TimeEvent.CURRENT_TIME_CHANGE, _onTimeChanged );
            //debug( "Media has a timeline" );

        }

    }

The first event, DURATION_CHANGE is fired at the beginning of the video, however the second one is never fired.

On which element should I attach the CURRENT_TIME_CHANGE event in order to track the current time of the video?

I have analyzed the Google Analytics plugin for OSMF that claims to track every 5,10 or 20 seconds, however looking at the code, it is not clear how it manages to track current time.


Solution

  • The solution was to add the time change event listener on the media player.

    First, one needs to pass a reference of the media player to the resource.

    In the main class for plugin, add the following after defining the pluginResource.

    pluginResource.addMetadataValue("MediaPlayer", mediaPlayer);
    

    Then, in the class that extends PluginInfo, override the initializePlugin method. Get hold of the MediaPlayer reference, and add the event listener.

    */ 
    override public function initializePlugin(resource:MediaResourceBase):void
    {
    var mediaPlayer:MediaPlayer = resource.getMetadataValue("MediaPlayer") as MediaPlayer;
    mediaPlayer.addEventListener(TimeEvent.CURRENT_TIME_CHANGE, _onTimeChanged);
    
     }
    
     private function _onTimeChanged(event:TimeEvent):void {
    
         trace("event.time", event.time);
      }
    

    For more info, see the advertisement plugin included in the OSMF source files (AdvertisementPluginInfo.as).