Posts made in June, 2013


One of the sites I manage, Late Night Record Pool, has been having bandwidth issues as of late. They enjoy roughly 8,000 unique visits a month, and with the ability to preview any song or video in their extensive library, the bandwidth adds up fast. We didn’t want to give up this awesome feature to the site, but we had to do something. So, I decided to try and come up with a way to just preview the songs, sending out only a fraction of the bandwidth every time. There are tons of classes and programs that offer up the ability to extract a section from an MP3, but they all require you to save the file before using it. That’s a good method, but with a library of music approaching two terabytes, suddenly adding a preview-version of every song would not be feasible. I had to come up with a way on my own to do it on the fly. $getID3 = new getID3(); $id3_info = $getID3->analyze($filename); list($t_min, $t_sec) = explode(':', $id3_info['length']); $time = ($t_min * 60) + $t_sec; $preview = $time / 30; // Preview time of 30 seconds $handle = fopen($filename, 'r'); $content = fread($handle, filesize($filename)); $length = strlen($content); if (!$session->IsLoggedIn()) { $length = round(strlen($content) / $preview); $content = substr($content, $length * .66 /* Start extraction ~20 seconds in */, $length); } header("Content-Type: {$id3_info['mime_type']}"); header("Content-Length: {$length}"); print $content; Note: the site from which I’m pulling this example also uses the getID3 PHP library to get information like Artist, Title, Mime-Type, etc. Now that you’ve read over the code, let’s go back and look at the important lines. Lines 5 and 6 break down the runtime of the entire song (in minutes:seconds) to give us the total number of seconds. From there, a little math on line 8 to get us the exact proportion 30 seconds would be on this song. Next, we bring the MP3 file into the code; Lines 10 and 11 use the fread method to read the file into the variable $content. We now have a (very large) string representing the MP3. After we pull the file in, and if the user is a logged-in user, we simply output our headers and print this string out. Because of the headers and string we send, the browser will interpret the script as an actual MP3 file and start playing/downloading. The IF block starting at line 15 handles the preview functionality for users who are not logged in. Using the proportion value we found at line 8, we then calculate out how many bytes will equal 30 seconds for this particular song, and we substr...

Read More