Wednesday, 7 September 2011

Youtube API(Upload video to our website)

First, download Zend Framework......

<?php

//debug
#error_reporting(E_ALL);

//include Zend Gdata Libs
require_once("Zend/Gdata/ClientLogin.php");
require_once("Zend/Gdata/HttpClient.php");
require_once("Zend/Gdata/YouTube.php");
require_once("Zend/Gdata/App/MediaFileSource.php");
require_once("Zend/Gdata/App/HttpException.php");
require_once('Zend/Uri/Http.php');

//yt account info
$yt_user = ' '; //youtube username or gmail account
$yt_pw = '  '; //account password
$yt_source = 'jh'; //name of application (can be anything)

//video path
$video_url = '1.mov';

//yt dev key
$yt_api_key = 'AI39s...'; //your youtube developer key

//login in to YT
$authenticationURL= 'https://www.google.com/youtube/accounts/ClientLogin';
$httpClient = Zend_Gdata_ClientLogin::getHttpClient(
$username = $yt_user,
$password = $yt_pw,
$service = 'youtube',
$client = null,
$source = $yt_source, // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);

$yt = new Zend_Gdata_YouTube($httpClient, $yt_source, NULL, $yt_api_key);

$myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$filesource = $yt->newMediaFileSource($video_url);
$filesource->setContentType('video/quicktime'); //make sure to set the proper content type.
$filesource->setSlug('1.mov');

$myVideoEntry->setMediaSource($filesource);

$myVideoEntry->setVideoTitle('name');
$myVideoEntry->setVideoDescription('desc');
// Note that category must be a valid YouTube category !
$myVideoEntry->setVideoCategory('Comedy');

// Set keywords, note that this must be a comma separated string
// and that each keyword cannot contain whitespace
$myVideoEntry->SetVideoTags('cars, funny');

// Upload URI for the currently authenticated user
$uploadUrl = "http://uploads.gdata.youtube.com/feeds/users/$yt_user/uploads";
// Try to upload the video, catching a Zend_Gdata_App_HttpException
// if availableor just a regular Zend_Gdata_App_Exception

try {
$newEntry = $yt->insertEntry($myVideoEntry,
$uploadUrl,
'Zend_Gdata_YouTube_VideoEntry');
} catch (Zend_Gdata_App_HttpException $httpException) {
echo $httpException->getRawResponseBody();
} catch (Zend_Gdata_App_Exception $e) {
echo $e->getMessage();
}

//this outputs a ton of garbage. not sure what to do with it yet.

/*echo "
" . var_dump($newEntry) . "

";
echo "

";*/

$state = $newEntry->getVideoState();

if ($state) {
ehco 'Upload status for video ID ' . $newEntry->getVideoId() . ' is ' .
$state->getName() . ' - ' . $state->getText() . "\n";

} else {
echo "Not able to retrieve the video status information yet. " .
"Please try again later.\n";

}

?>