Hongmu Notes
Home Language Notes php convert lyrics of lrc file to str subtitles
Language Notes PHP

php convert lyrics of lrc file to str subtitles

php convert lyrics of lrc file to str subtitles

This function is a PHP script designed to convert lyric files into SRT subtitle files. The specific implementation process is as follows:

  • Remove extra blank lines using a regular expression. preg_replace("/^\s*$/m", "", $lrc)
  • Split the lyrics text into lines and use it. explode("\n", $lrc)
  • Iterate over each line of lyrics using a regular expression. preg_match_all("/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/", $lines[$i], $matches) Match time labels with lyrics content.
  • If a time tag is matched, retrieve the start and end times. If the lyrics follow directly after the last time tag, calculate the end time based on the time tag in the next line; otherwise, set the end time to the start time plus 5 seconds.
  • Generate SRT subtitle content based on start and end times as well as the song lyrics, then save it. $srt In a string.
  • Return $srt alphabetic string.

This function is primarily used to convert LRC-format lyrics into SRT-format subtitles, making it easier to display the lyrics within a video player.

Code:

function lrc2srt($lrc) {
    // print_r($lrc);
    // 去除多余的空白行
    $lrc = preg_replace("/^\s*$/m", "", $lrc);
    
    // 按行分割
    $lines = explode("\n", $lrc);
    $count = count($lines);
    // print_r($lines);
    $srt = '';
    $index = 1;
    for ($i = 0; $i < $count; $i++) {
        // 匹配时间标签和歌词内容
        preg_match_all("/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/", $lines[$i], $matches);
        // print_r($matches);
        if (!empty($matches[0])) {
            // 获取时间标签
            $startHour = intval($matches[1][0]);
            $startMinute = intval($matches[2][0]);
            $startSecond = intval($matches[3][0]);
            // $startTime = sprintf("%02d:%02d:%02d,%03d", 0,$startHour, $startMinute, $startSecond);
            $startTime = sprintf('%02d:%02d:%02d,%03d', 0, $startHour, $startMinute, $startSecond * 10);

            // 获取歌词内容
            if (strpos($lines[$i], ']') === false) {
                // 特殊情况:歌词内容直接跟在最后一个时间标签之后的情况
                $lyric = trim(substr($lines[$i], strlen($matches[0][0])));

                if ($i < $count - 1 && strpos($lines[$i + 1], '[') !== false) {
                    // 下一行是新的时间标签,计算结束时间
                    preg_match_all("/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/", $lines[$i + 1], $nextMatches);
                    $endHour = intval($nextMatches[1][0]);
                    $endMinute = intval($nextMatches[2][0]);
                    $endSecond = intval($nextMatches[3][0]);
                } else {
                    // 下一行无新的时间标签,将结束时间设为开始时间+5秒
                    $endHour = $startHour;
                    $endMinute = $startMinute;
                    $endSecond = $startSecond + 5;
                }
            } else {
                $lyric = trim(preg_replace("/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/", "", $lines[$i]));

                // 获取下一行的时间标签
                preg_match_all("/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/", $lines[$i + 1], $nextMatches);

                if (!empty($nextMatches[0])) {
                    // 计算结束时间
                    $endHour = intval($nextMatches[1][0]);
                    $endMinute = intval($nextMatches[2][0]);
                    $endSecond = intval($nextMatches[3][0]);
                } else if ($i !== $count - 1) {
                    // 下一行无时间标签,将结束时间设为开始时间+5秒
                    $endHour = $startHour;
                    $endMinute = $startMinute;
                    $endSecond = $startSecond + 5;
                }
            }

            // 计算结束时间
            // $endTime = sprintf("%02d:%02d:%02d,%03d", 0, $endHour, $endMinute, $endSecond);
            $endTime = sprintf('%02d:%02d:%02d,%03d', 0, $endHour, $endMinute, ($endSecond - 5) * 10);

            if(!empty($lyric)){
                // 构建SRT字幕内容
                $srt .= $index . "\n";
                $srt .= $startTime . ' --> ' . $endTime . "\n";
                $srt .= $lyric . "\n\n";
    
                $index++;
            }
        }
    }

    return $srt;
}
}
微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

Wood-grain flooring & wall tile website template – 0933

Wood-grain flooring & wall tile website template – 0933 Practical Collection Yiyou template

An eYouCMS website template designed for the wood-grain flooring and wall tile industries. Its modern home decoration design style is ideal for showcasing flooring products, wall tile collections, spatial arrangements, and brand stories. This template helps building materials brands showcase their products online and attract both renovation companies and homeowners. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for eYouCMS | eYouCMS...
👁 61
Wood Preservation & Building Materials Website Template 0257

Wood Preservation & Building Materials Website Template 0257 Practical Collection Yiyou template

This EyouCMS template is ideal for the wood, preservative-treated wood, and building materials industries. Its natural and minimalist design effectively showcases preservative-treated wood products, timber and construction materials, project cases, and brand stories. It helps wood-based enterprises showcase their products online and attract clients in the construction and outdoor industries. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 40
(Adaptive mobile version) Responsive news blog – Knowledge-based PbootCMS website template; Download source code for a self-media operation blog website – 0778

(Adaptive mobile version) Responsive news blog – Knowledge-based PbootCMS website template; Download source code for a self-media operation blog website – 0778 Practical Collection pbootcms Template

A responsive news blog and self-media management PbootCMS website template, compatible with both PC and WAP devices. The clean, information-flow design is ideal for self-media creators to share industry trends, operational tips, and personal insights. It helps self-media creators build online influence and cultivate an engaged follower base. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.c...
👁 53
(PC+WAP) black doors and windows custom website pbootcms template hardware and building materials industry website source code download 0132

(PC+WAP) black doors and windows custom website pbootcms template hardware and building materials industry website source code download 0132 Practical Collection pbootcms Template

A PbootCMS website template designed for the custom window and door manufacturing as well as the hardware and building materials industry, compatible with both PC and mobile devices. Its modern and sophisticated design effectively showcases your window and door product ranges as well as your strong presence in the building materials trade. This template helps window and door brands or building materials companies create a professional online brand presence, thereby enhancing their marketing and promotional effectiveness. Template Display | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password:...
👁 45
mysqli_free_result() expects parameter 1 to be mysqli_result, object given in

mysqli_free_result() expects parameter 1 to be mysqli_result, object given in Summary of pitfalls

This error usually means that you are trying to free an invalid result set object using the mysqli_free_result() function. This may be because you are trying to free a result set that has already been freed, or you are trying to free something that is not a result set object. To resolve this issue, make sure you are passing a valid result set object to the mysqli_free_result() function. You…
👁 219
Corrosion-resistant wood products construction website template 0934

Corrosion-resistant wood products construction website template 0934 Practical Collection Yiyou template

This EyouCMS template is ideal for the防腐木制品 and construction industries. Its natural and minimalist design style is perfect for showcasing防腐木 products, building materials, project cases, and brand stories. It helps wood-based enterprises showcase their products online and attract clients in the construction and outdoor sectors. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 43