Luuk Bruins
Luuk Bruins

Reputation: 11

mediaelement.js - Play random video?

I have lots of videos in the directory "video" in my WordPress installation.

They all play nice using the MediaElement.js plugin, but is it also possible to play a random clip from this directory? For example using a shortcode that directs to the directory (and not to a specific video), something like

[video src="http://www.domain.com/wordpress/wp-content/video" random="true"]

That would be great!

Upvotes: 1

Views: 476

Answers (1)

This should be possible.

What you might want to do is use AJAX to generate the div containing your video player. If you do this, you can delete/recreate the player very easily.

After that what you'd need is a shortcode definition which feeds a directory string value and a boolean value into whichever function you attach to the shortcode handler.

For Instance

$defaultDirectory=site_url()+"/videos/";

add_shortcode( 'video', 'videoDiv' );

function videoDiv( $shortcodeAttributeList )
{
  extract( shortcode_atts( array(
             'src'    => $defaultDirectory,
             'random' => true,              /*set default values, use lowercase*/
         ), $shortcodeAttributeList ) );

  if($random)
  {
      $numFiles=fileCounter($src);
      $choice=rand(1, $numFiles);
  }

  $output='<div id="videoPlayer" class="player">';
  // Continue by making a string which spans from <div> to </div>

  return $output; //a div
}

Also from http://php.net/manual/en/function.readdir.php

<?php
/**
* get the number of files within a given dir
*/
function fileCounter($dir){
    $counter = 0;
    if ($handle = opendir($dir)) {
      //echo "Directory handle: $handle\n";
      //echo "Files:\n";
      /* This is the correct way to loop over the directory. */
      while (false !== ($file = readdir($handle))) {
          //echo "<BR>".$counter." - $file";
          $counter++;
      }
      closedir($handle);
    }
    $counter -= 1; // in order to exclude '.' and '..', as well as start the counter on 1
    return $counter;
}
/**
* get the filename in a giver dir, starting the first file with the index 1
*/
function fileNameByIndex($dir, $fileIndex){
    $counter = 0;
    if ($handle = opendir($dir)) {
      while (false !== ($file = readdir($handle))) {
          $counter++;
          if($counter - 2 == $fileIndex)
              return $file;
      }
      closedir($handle);
    }
    return "";
}
}    

Upvotes: 1

Related Questions