Thursday, December 31, 2015

Youtube API v3 - Get upload progress while uploading a video to YouTube

If you want to use YouTube API v3 from PHP, you will probably want to retrieve some kind of upload progress metric while your video is being transferred to YouTube.
If you check YouTube API documentation , especially videos.insert() function, you'll probably be disappointed. JavaScript version of file upload fully supports the upload progress retrieval, but PHP example has no notion of anything similar.

However, we can do something about it. Here's an idea:

If you carefully check the PHP example, you will see that current progress is easily obtainable in the while loop which sends your video chunk by chunk. We should grab this information, store it to a database or a file, and we're good to go.

For example, our loop might look like this:

<?php

 while (!$status && !feof($handle)) {
            $chunk = fread($handle, $chunkSizeBytes);

            $progress= $media->getProgress();

            $progress = $progress / ( $filesize * 1.0) * 100;

            $db->ExecuteUpdate("UPDATE progress_info SET Val= ?  WHERE KeyX=? AND UID=? " , array($progress , "progress" ,$UID ));

            $status = $media->nextChunk($chunk);
        }


?>


Now, if we want to retrieve current video's upload progress, we just query our database using AJAX. AJAX opens a tiny PHP script which reads the current video upload information from database.
Here's a sample script:

<?php

$UID = $reqHelper->GetParam("uid");

$res = $db->ExecuteSelect("SELECT * FROM progress_info WHERE KeyX=? AND UID=?" , array("progress" , $UID ) );

$row = $db->FetchRow($res);

$val = $row['Val'];

echo round($val,2) .  "%";

?>

And that's it!

If you need help coding this, just let me know, I will throw in some sample code.

No comments:

Post a Comment

Ubuntu 12.04, 14.04, 16.04 - auto start an app or script before login

To run a command or application at startup, even before the user has logged in, you can use this file: /etc/rc.local The commands entered...