Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
YouTube to Mp3 PHP Script Code
08-24-2011, 03:36 PM (This post was last modified: 10-19-2012 06:03 PM by Stephen.)
Post: #1
YouTube to Mp3 PHP Script Code
Recently, I reeeaally wanted an MP3 audio version of a certain YouTube.com video. I was tired of the online apps that either didn't work or charged you for this service, so I decided to write my own. It was a tad confusing, so I thought I'd share my mini-app with the world to help others who might undertake such an endeavor.

I created the app for my own personal use to run on my Windows development machine using the latest version of XAMPP. I chose this environment for my app because, in this way, I have complete control over server and PHP configurations. And manipulating video and audio files is just plain easier that way. Thus, I suspect that this app won't run in most shared hosting environments (i.e., on a commercial server run by a web hosting company). You'll have to tweak my code in that case...

So, first of all, you will need to download the latest FFmpeg build. I used the Windows 32-bit version. FFmpeg is the software that will ultimately enable you to convert YouTube's FLV video files into MP3 audio files.

Inside the FFmpeg distribution is a /bin/ folder that contains the only file that you'll need: ffmpeg.exe. I have the file in my project/app folder in the web root (htdocs in XAMPP), but you may want to put the file (and other app files/directories) beneath the web root and reference it there (i.e., in a production environment). It's not required for my app to function, but, on a production server, I'm in the habit of putting files there that don't need to be publicly accessible, for extra security. It's your prerogative.

With that in place, you can put both the converter class (YouTubeToMp3Converter.class.php) and example implementation (index.php) into your web root project directory as well. See below for both files:

YouTubeToMp3Converter.class.php

PHP Code:
<?php 

    
// Conversion Class 
    
class YouTubeToMp3Converter 
    

        
// Private Fields 
        
private $_songFileName ''
        private 
$_flvUrl ''
        private 
$_audioQualities = array(64128320); 
        private 
$_tempVidFileName
        private 
$_vidSrcTypes = array('source_code''url'); 

        
// Constants 
        
const _TEMPVIDDIR 'videos/'
        const 
_SONGFILEDIR 'mp3/'
        const 
_FFMPEG 'ffmpeg.exe'
         
        
#region Public Methods 
        
function __construct() 
        { 
        } 
         
        function 
DownloadVideo($youTubeUrl
        { 
            
$file_contents file_get_contents($youTubeUrl); 
            if (
$file_contents !== false
            { 
                
$this->SetSongFileName($file_contents); 
                
$this->SetFlvUrl($file_contents); 
                if (
$this->GetSongFileName() != '' && $this->GetFlvUrl() != ''
                { 
                    return 
$this->SaveVideo($this->GetFlvUrl()); 
                } 
            } 
            return 
false
        }  
         
        function 
GenerateMP3($audioQuality
        { 
            
$qualities $this->GetAudioQualities(); 
            
$quality = (in_array($audioQuality$qualities)) ? $audioQuality $qualities[1];             
            
$exec_string self::_FFMPEG.' -i '.$this->GetTempVidFileName().' -y -acodec libmp3lame -ab '.$quality.'k '.$this->GetSongFileName(); 
            
exec($exec_string); 
            
$this->DeleteTempVid(); 
             return 
is_file($this->GetSongFileName()); 
        } 
         
        function 
ExtractSongTrackName($vidSrc$srcType
        { 
            
$name ''
            
$vidSrcTypes $this->GetVidSrcTypes(); 
            if (
in_array($srcType$vidSrcTypes)) 
            { 
                
$vidSrc = ($srcType == $vidSrcTypes[1]) ? file_get_contents($vidSrc) : $vidSrc
                if (
$vidSrc !== false && eregi('eow-title',$vidSrc)) 
                { 
                    
$name end(explode('eow-title',$vidSrc)); 
                    
$name current(explode('">',$name)); 
                    
$name ereg_replace('[^-_a-zA-Z,"\' :0-9]',"",end(explode('title="',$name))); 
                } 
            } 
            return 
$name
        }         
        
#endregion 

        #region Private "Helper" Methods 
        
private function SaveVideo($url
        { 
            
$this->SetTempVidFileName(time()); 
            
$file fopen($this->GetTempVidFileName(), 'w'); 
            
$ch curl_init(); 
            
curl_setopt($chCURLOPT_FILE$file); 
            
curl_setopt($chCURLOPT_HEADER0); 
            
curl_setopt($chCURLOPT_URL$url); 
            
curl_setopt($chCURLOPT_FOLLOWLOCATION1); 
            
curl_setopt($chCURLOPT_COOKIEFILECOOKIE); 
            
curl_setopt($chCURLOPT_COOKIEJARCOOKIE); 
            
curl_exec($ch); 
            
curl_close($ch); 
            
fclose($file); 
            return 
is_file($this->GetTempVidFileName()); 
        } 
         
        private function 
DeleteTempVid() 
        { 
            if (
is_file($this->GetTempVidFileName()))  
            { 
                
unlink($this->GetTempVidFileName()); 
            }         
        } 
        
#endregion 
         
        #region Properties 
        
public function GetSongFileName() 
        { 
            return 
$this->_songFileName
        }         
        private function 
SetSongFileName($file_contents
        { 
            
$vidSrcTypes $this->GetVidSrcTypes(); 
            
$trackName $this->ExtractSongTrackName($file_contents$vidSrcTypes[0]); 
            
$this->_songFileName = (!empty($trackName)) ? self::_SONGFILEDIR preg_replace('/_{2,}/','_',preg_replace('/ /','_',preg_replace('/[^A-Za-z0-9 _-]/','',$trackName))) . '.mp3' ''
        } 

        public function 
GetFlvUrl() 
        { 
            return 
$this->_flvUrl
        }             
        private function 
SetFlvUrl($file_contents
        {  
            
$vidUrl ''
            if (
eregi('fmt_url_map',$file_contents)) 
            { 
                
$vidUrl end(explode('&fmt_url_map=',$file_contents)); 
                
$vidUrl current(explode('&',$vidUrl)); 
                
$vidUrl current(explode('%2C',$vidUrl)); 
                
$vidUrl urldecode(end(explode('%7C',$vidUrl))); 
            } 
            
$this->_flvUrl $vidUrl
        } 
         
        public function 
GetAudioQualities() 
        { 
            return 
$this->_audioQualities
        }     
         
        private function 
GetTempVidFileName() 
        { 
            return 
$this->_tempVidFileName
        } 
        private function 
SetTempVidFileName($timestamp
        { 
            
$this->_tempVidFileName self::_TEMPVIDDIR $timestamp .'.flv'
        } 
         
        public function 
GetVidSrcTypes() 
        { 
            return 
$this->_vidSrcTypes
        } 
        
#endregion 
    

     
?>

index.php

PHP Code:
<?php echo '<?xml version="1.1" encoding="iso-8859-1"?>'?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> 
<head> 
    <title>YouTube-To-Mp3 Converter</title> 
    <style type="text/css"> 
        body 
        { 
            text-align:center; 
            font:13px Verdana,Arial; 
            margin-top:50px; 
        } 
         
        p 
        { 
            margin:15px 0; 
            font-weight:bold; 
        } 
         
        form 
        { 
            width:450px; 
            margin:0 auto; 
            padding:15px; 
            border:1px solid #ccc; 
        } 
         
        form input[type="text"] 
        { 
            width:385px; 
        } 
         
        form p 
        { 
            margin:10px 0; 
            font-weight:normal; 
        } 
    </style> 
</head> 
<body> 
    <h2>YouTube-To-Mp3 Converter</h2> 
    <?php 
        
// Execution settings 
        
ini_set('max_execution_time',0); 
        
ini_set('display_errors',0);         
         
        
// On form submission... 
        
if ($_POST['submit']) 
        { 
            
// Instantiate converter class 
            
include 'YouTubeToMp3Converter.class.php'
            
$converter = new YouTubeToMp3Converter();             
             
            
// Print "please wait" message and preview image 
            
$vidID $vidTitle ''
            
$urlQueryStr parse_url(trim($_POST['youtubeURL']), PHP_URL_QUERY); 
            if (
$urlQueryStr !== false && !empty($urlQueryStr)) 
            { 
                
$kvPairs explode('&'$urlQueryStr); 
                foreach (
$kvPairs as $v
                { 
                    
$kvPair explode('='$v); 
                    if (
$kvPair[0] == 'v'
                    { 
                        
$vidID $kvPair[1]; 
                        break; 
                    } 
                } 

                echo 
'<div id="preview" style="display:block"><p>...Please wait while I try to convert:</p>'
                echo 
'<p><img src="http://img.youtube.com/vi/'.$vidID.'/1.jpg" alt="preview image" /></p>'
                echo 
'<p>'.$converter->ExtractSongTrackName(trim($_POST['youtubeURL']), 'url').'</p></div>'
                
flush(); 
            } 
             
            
// Main Program Execution 
            
if ($converter->DownloadVideo(trim($_POST['youtubeURL']))) 
            { 
                echo (
$converter->GenerateMP3($_POST['quality'])) ? '<p>Success!</p>' '<p>Error generating MP3 file!</p>'
            } 
            else 
            { 
                echo 
'<p>Error downloading video!</p>'
            } 
        } 
    
?> 
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 
        <p>Enter a valid YouTube.com video URL:</p> 
        <p><input type="text" name="youtubeURL" /></p> 
        <p><i>(i.e., "<span style="color:red">http://www.youtube.com/watch?v=HMpmI2F2cMs</span>")</i></p> 
        <p style="margin-top:20px">Choose the audio quality (better quality results in larger files):</p> 
        <p style="margin-bottom:25px"><input type="radio" value="64" name="quality" />Low &nbsp; <input type="radio" value="128" name="quality" checked="checked" />Medium &nbsp; <input type="radio" value="320" name="quality" />High</p> 
        <p><input type="submit" name="submit" value="Create MP3 File" /></p> 
    </form> 
    <script type="text/javascript"> 
        window.onload = function() 
        { 
            if (document.getElementById('preview')) 
            { 
                document.getElementById('preview').style.display = 'none'; 
            } 
        }; 
    </script> 
</body> 
</html> 

YouTube FLV files are temporarily stored during conversion).

To help you visualize, in XAMPP, my final directory structure appears as follows:

C:\xampp\htdocs\VideoToMp3Converiter\mp3
C:\xampp\htdocs\VideoToMp3Converter\videos
C:\xampp\htdocs\VideoToMp3Converter\ffmpeg.exe
C:\xampp\htdocs\VideoToMp3Converter\index.php
C:\xampp\htdocs\VideoToMp3Converter\YouTubeToMp3Converter.class.php

I'll let you figure out the majority of the code on your own. In a nutshell, the converter class grabs the YouTube FLV url using some regex, downloads the video with cURL, then converts the FLV to MP3 audio by invisibly running FFmpeg in a command shell (with PHP's exec()).

A few things:

1) As I said earlier, the app won't run on commercial servers that have disabled shell access (see use of exec() function in code).

2) The regex to get the FLV urls (and other video information) will undoubtedly break the next time Google drastically overhauls their site....which they did recently....Alternatively, there is probably some API available for grabbing the videos, and maybe one of these days I will integrate that into the code.

3) If you need help with FFmpeg command line flags and general syntax, take a look at the FFmpeg documentation.

4) You will probably want to add some additional data validation/sanitization, as I only coded the minimum required for my needs.


//Greets to CodingForum.

Need Game or IRC Hosting? Get it now on xShellz.com !

The best web hosting only on BeltHosting.com

[Image: logo.png]
User Tools
Quote this message in a reply
09-16-2012, 01:27 AM
Post: #2
RE: YouTube to Mp3 PHP Script Code
Hi,

This post and code was unceremoniously ripped from the original forum thread at CodingForums.com.

The code here is outdated and no longer works.

If you are interested in the original, functioning PHP code for converting YouTube.com videos to various file formats, then please visit my original thread at CodingForums.com.

Thanks,

The Author of this Code
User Tools
Quote this message in a reply
12-08-2012, 07:12 PM
Post: #3
RE: YouTube to Mp3 PHP Script Code
(09-16-2012 01:27 AM)chump2877 Wrote:  Hi,

This post and code was unceremoniously ripped from the original forum thread at CodingForums.com.

The code here is outdated and no longer works.

If you are interested in the original, functioning PHP code for converting YouTube.com videos to various file formats, then please visit my original thread at CodingForums.com.

Thanks,

The Author of this Code

As you can see, I left greets to CodingForum.

Need Game or IRC Hosting? Get it now on xShellz.com !

The best web hosting only on BeltHosting.com

[Image: logo.png]
User Tools
Quote this message in a reply
Post Reply 


Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Create a script like speedtest.net Speed Test PHP Script Stephen 3 31,123 03-21-2012 08:50 PM
Last Post: Stephen
  Speedtest Upload Script raul23 1 5,816 12-18-2011 09:38 PM
Last Post: Stephen
  Send SMS Script PHP Code Stephen 2 5,821 10-10-2011 01:33 AM
Last Post: Stephen



User(s) browsing this thread:
1 Guest(s)