Song Lyrics: lrc2srt and srt2json


Hits: 84  

LRC2SRT.php

<?php

function lrc2srt( $lrc ) {
	$lrc = explode( "\n", $lrc );
	$srt = "";
	$lines = array();
	foreach ( $lrc as $lrcl ) {
		if ( preg_match( "|\[(\d\d)\:(\d\d)\.(\d\d)\](.+)|", $lrcl, $m ) ) {
			$lines[] = array(
				'time' => "00:{$m[1]}:{$m[2]},{$m[3]}0", // convert to SubRip-style time
				'lyrics' => trim( $m[4] )
			);
		}
	}
	for ( $i = 0; $i < count( $lines ); $i++ ) {
		$n = $i + 1;
		$nexttime = isset( $lines[$n]['time'] ) ? $lines[$n]['time'] : "99:00:00,000";
		$srt .= "$n\n"
		     .  "{$lines[$i]['time']} --> {$nexttime}\n"
		     .  "{$lines[$i]['lyrics']}\n\n";
	}
	return $srt;
}

echo "<pre>";
echo lrc2srt( file_get_contents("FileName.lrc") );
echo "</pre>";

?>

SRT2JSON.php

<?php

define('SRT_STATE_SUBNUMBER', 0);
define('SRT_STATE_TIME',      1);
define('SRT_STATE_TEXT',      2);
define('SRT_STATE_BLANK',     3);

$lines   = file("FileName.srt");

$subs    = array();
$state   = SRT_STATE_SUBNUMBER;
$subNum  = 0;
$subText = '';
$subTime = '';

foreach($lines as $line) {
    switch($state) {
        case SRT_STATE_SUBNUMBER:
            $subNum = trim($line);
            $state  = SRT_STATE_TIME;
            break;

        case SRT_STATE_TIME:
            $subTime = trim($line);
            $state   = SRT_STATE_TEXT;
            break;

        case SRT_STATE_TEXT:
            if (trim($line) == '') {
                $sub = new stdClass;
                $sub->number = $subNum;
                list($sub->startTime, $sub->stopTime) = explode(' --> ', $subTime);
                $sub->text   = $subText;
                $subText     = '';
                $state       = SRT_STATE_SUBNUMBER;

                $subs[]      = $sub;
            } else {
                $subText .= $line;
            }
            break;
		
    }
		
}

echo "<pre>";
print_r($subs);
echo "</pre>";


$count = count($subs);
 
for($i=0;$i<$count;$i++)
{


$playlist['ID'.$i] = array($subs[$i]->text, $subs[$i]->startTime, $subs[$i]->startTime, $subs[$i]->stopTime);


}

echo  json_encode($playlist);

?>

Published by

Sandeep Verma

I’m an Entrepreneur. I’m proud to work as Blogger, LAMP Programmer, Linux Admin, Web Consultant, Cloud Manager, Apps Developer, Searcher. Concentrate > Observe > Imagine > Launch