Youtube now works in Corona! :D

Hi everyone!

After trying to get this to work by searching and testing some days a week I’ve finally got Youtube videos playing in an acceptable way using Corona SDK. :slight_smile:

Currently it connects to a PHP file on a server which collects the post data with the video URL and then sends it to another PHP file which is made by this guy: http://www.masnun.me/2011/05/17/phptube-a-php-class-to-get-download-links-from-youtube-watch-videos.html#comments

Almost everything works perfect!

My problem is that I can only get it to work if the server has the same ip-adress as the device because the URL that you gets only work on the device that requested it. So you can test this if you use something like xampp. I need a solution that makes it possible to have the PHP files in the project folder or have them on a server with another IP-adress and make it work anyway.

Here is my project:
http://d.pr/f/oEqd

And here is the code, change the URL in main.lua to test it with other videos:

main.lua

io.output():setvbuf('no')  
print();print("");print()  
  
-- require controller module  
local storyboard = require "storyboard"  
local widget = require "widget"  
  
http = require("socket.http")  
ltn12 = require("ltn12")  
url = require("socket.url")  
  
local is\_supported = audio.supportsSessionProperty  
if (is\_supported) then  
 audio.setSessionProperty(audio.MixMode, audio.AmbientMixMode)  
end  
  
-- load first screen  
  
-- The main group  
mainGroup = display.newGroup()  
  
-- The main function  
local function main()  
  
 -- Add the group from director class  
 --mainGroup:insert(director.directorView)  
 loggedin = nil  
 --storyboard.gotoScene( "mainpage" )  
  
 youtubeVideoURL = "http://www.youtube.com/watch?v=0e4p\_5J\_bZY"   
  
 local function networkListener( event )  
 if ( event.isError ) then  
 print( "Network error!")  
 else  
 print (event.response )  
 url = event.response  
 function trimr(s)  
 return s:find'^%s\*$' and '' or s:match'^(.\*%S)'  
 end  
 url = trimr(url)  
 media.playVideo( url, media.RemoteSource, true)  
 end  
 end  
  
 postData = "videoURL=" .. youtubeVideoURL  
  
 local params = {}  
 params.body = postData  
  
 network.request( "http://localhost/youtubedl/index.php", "POST", networkListener, params)  
  
 return true  
end  
  
main()  

index.php

<?php <br>require\_once 'PhpTube.php';  
$tube = new PhpTube();  
  
if (isset($\_POST['videoURL'])){  
 $videoURL = $\_POST['videoURL'];  
  
 $videos = $tube-\>getDownloadLink($videoURL);  
 echo($videos[0]);  
}  
  
?\>  

PhpTube.php

[code]

<?php
/\* \* @package PhpTube - A PHP class to get youtube download links \* @author Abu Ashraf Masnun
* @website http://masnun.com
*
*/

class PhpTube
{

/**
* Parses the youtube URL and returns error message or array of download links
*
* @param $watchUrl the URL of the Youtube video
* @return string|array the error message or the array of download links
*/
public function getDownloadLink($watchUrl)
{
//utf8 encode and convert "&"
$html = utf8_encode($this->_getHtml($watchUrl));
$html = str_replace("\u0026amp;","&",$html);

//get format url
preg_match_all('/url_encoded_fmt_stream_map\=(.*)/',$html,$matches);
$formatUrl = urldecode($matches[1][0]);

//split the format url into individual urls
$urls = preg_split('/url=/', $formatUrl);

$videoUrls = array();

foreach($urls as $url)
{

// do necessary processings
$url = urldecode($url);
$urlparts = explode(";",$url);
$url = $urlparts[0];
$urlparts = explode(",",$url);
$url = $urlparts[0];




// append to container
if(strlen($url) > 450 && strlen($url) < 600)
{
$length = strlen($url);
$characters = 3;
$start = $length - $characters;
$end = substr($url , $start ,$characters);
if($end == "mp4" ){
$videoUrls[] = $url;
}

}
}

return $videoUrls;
}

/**
* A wrapper around the cURL library to fetch the content of the url
*
* @throws Exception if the curl extension is not available (or loaded)
* @param $url the url of the page to fetch the content of
* @return string the content of the url
*/
private function _getHtml($url)
{
if (function_exists("curl_init"))
{

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
return curl_exec($ch);
}
else
{
throw new Exception("No cURL module available");
}
}

}

[/code] [import]uid: 24111 topic_id: 25783 reply_id: 325783[/import]

Solved it with this code! :smiley:

This doesn’t need any server, just this code and file!

main.lua

[code]
io.output():setvbuf(‘no’)
print();print("");print()

– The main group
mainGroup = display.newGroup()

– The main function
local function main()

local function split(str, c)
a = string.find(str, c)
str = string.gsub(str, c, “”, 1)
aCount = 0
start = 1
array = {}
last = 0

while a do
array[aCount] = string.sub(str, start, a - 1)
start = a
a = string.find(str, c)

str = string.gsub(str, c, “”, 1)
aCount = aCount + 1
end

return array
end

youtubeVideoURL = “http://www.youtube.com/watch?v=MCWJUSulnro

local function networkListener( event )
if ( event.isError ) then
print( “Network error!”)
else

response = event.response
responseArray = split(response, “http”)
–print (responseArray[28])

for i=0, #responseArray do
if (string.find(responseArray[i], “mp4”)) ~= nil then
url = responseArray[i]
break
end

end

url = “http”…url

–url = string.gsub(url, “ip=212”, “ip=”…ipArray[0])
url = string.gsub(url,"%%253A",":")
url = string.gsub(url,"%%252F","%/")
url = string.gsub(url, “%%253F”, “%?”)
url = string.gsub(url, “%%253D”, “%=”)
url = string.gsub(url, “%%3D”, “%=”)
url = string.gsub(url, “%%2526”, “%&”)
url = string.gsub(url, “%%26”, “%&”)
url = string.gsub(url, “%%25252”, “%%2”)
url = string.gsub(url, “%%2C907217”, “”)

_start, _end = string.find(url, “mp4”);
url = string.sub(url, 1, _end)

media.playVideo( url, media.RemoteSource, true) --]]
end
end

postData = “videoURL=” … youtubeVideoURL

local params = {}
params.body = postData

network.request( youtubeVideoURL, “GET”, networkListener)

return true
end

main()
[/code] [import]uid: 24111 topic_id: 25783 reply_id: 104251[/import]

I copy/pasted your code and it doesn’t work. There’s no instance of “mp4” anywhere in the event.response. [import]uid: 44647 topic_id: 25783 reply_id: 104256[/import]

What youtube URL did you use? [import]uid: 24111 topic_id: 25783 reply_id: 104263[/import]

Hi. I just tested your code above and it failed (no response) in the simulator. I used the same youtubeurl as you posted. Do we need to test this on a real device? [import]uid: 125239 topic_id: 25783 reply_id: 104264[/import]

I just tried copy pasting it to a new file and it worked :confused:

What Corona build are you using? [import]uid: 24111 topic_id: 25783 reply_id: 104265[/import]

I’ve tried with 2012.797 & 2012.799 and they both failed: attempt to concatenate global ‘url’ (a nil value)

I’m on Windows using Cider by the way. Gimme a second and I’ll try on a Mac. [import]uid: 125239 topic_id: 25783 reply_id: 104266[/import]

I’m using build 786 (haven’t tested a later one) on Mac :wink: [import]uid: 24111 topic_id: 25783 reply_id: 104267[/import]

Just tried on my Mac and that failed as well.
Could this have something to do with my location - I’m located in Europe? [import]uid: 125239 topic_id: 25783 reply_id: 104268[/import]

I’m on 797. I suggest you upgrade and see if it still works for you.

EDIT: doesn’t work on 785 here. [import]uid: 44647 topic_id: 25783 reply_id: 104271[/import]

I’m also located in Europe, will try to upgrade Corona and test again. [import]uid: 24111 topic_id: 25783 reply_id: 104272[/import]

What errors does people get?
Does it work for anyone?! (more than me ofc :wink: ) [import]uid: 24111 topic_id: 25783 reply_id: 104273[/import]

It works with build 799 [import]uid: 24111 topic_id: 25783 reply_id: 104274[/import]

Are you saying that we only need your code from main.lua in post #1 and none of the php files for this to work? [import]uid: 71201 topic_id: 25783 reply_id: 104279[/import]

No forget all about post #1, only use the code in post #2 [import]uid: 24111 topic_id: 25783 reply_id: 104285[/import]

I think I found the error…sort of.
If I goto the Youtube URL you provided in IE on my computer I need to login using a Google account because of the content. So I tried with another URL: http://www.youtube.com/watch?v=b0QkF3P58dU
But I still don’t see anything in the simulator.

EDIT: It works on the Mac simulator but not on Windows. Thanks for posting this I appreciate it! [import]uid: 125239 topic_id: 25783 reply_id: 104276[/import]

Good catch. It’s not going to work for content that requires you to be logged in unless some other criteria are met. [import]uid: 44647 topic_id: 25783 reply_id: 104286[/import]

toby2: I can watch videos that requires me to be logged in even while I’m not. Are you on Mac or Windows? [import]uid: 24111 topic_id: 25783 reply_id: 104347[/import]

Mac. [import]uid: 44647 topic_id: 25783 reply_id: 104351[/import]

Okay, can you give me Youtube watch URL that doesn’t work for you? [import]uid: 24111 topic_id: 25783 reply_id: 104451[/import]