Search code examples
phpyoutubemp3download

Downloading youtubevideos to server with php


So i want to download youtubevideos as mp3 to my server, so i can listen them easily as mp3.

I have some ecperience in PHP, and second to none in youtube API, but if i have understood correctly youtubevideos are loaded in chunks, and 1 of them is the mp3 soundtrack of the video.

If that is incorrect, could you advice other way to do the downloading?

To this point i have managed to do small php script to get the nessessary information to save the audio.

$id =  $_POST["A"];
$xmlData = simplexml_load_string(file_get_contents("http://gdata.youtube.com/feeds/api/videos/{$id}?fields=title"));

$title = (string)$xmlData->title;

$bad = array_merge(
        array_map('chr', range(0,31)),
        array("<", ">", ":", '"', "/", "\\", "|", "?", "*"));
$result = str_replace($bad, "-", $title);


$file = "$result.mp3";
fopen("$file", 'w+') or die('Cannot open file:  '."$file");
//echo "http://youtubeinmp3.com/fetch/?video=http://www.youtube.com/watch?v=$id";
$current = file_get_contents("$file");
//$current .= "http://youtubeinmp3.com/fetch/?video=http://www.youtube.com/watch?v=$id";
file_put_contents("$file", $current);

(post A is coming from my html part of code and it includes youtube video ID)

So, in that code i dont exactly use youtube to download the mp3 track... so it would be great if any of you would know how to download it directly from youtube, and how to save it, because by my logick that code should perfectly work, and it does, untill the saving the audio, it saves about 50 bits and then stops, i dont get any errors or anything so its realy hard to debug.

Also if you notice any errors os better ways to do things in my code pleace notify me.

Also sorry for my bad english i m from finland, and yes sorry for crappy code, this is actualy first practical program i would be going to use :)


Solution

  • Youtube API doesn't provide direct links to audio or video content, only thumbnails. The only way is to parse regular page using regular expression to extract link to media. Thats how all "getfromyoutube" sites doing.

    After you get content you can process it with ffmpeg or other tool. I don't think there is separate mp3 track. Normally audio track is embedded to mp4 container.

    Yet it is illegal and you shouldn't doing this. e.t.c. e.t.c. I warned you ;)