5月 25, 2021 - laravel, php开发    php获取视频时长已关闭评论

php获取视频时长

1:下载安装包:
composer require james-heinrich/getid3
2:封装方法:
注意:是在Laravel6.x的框架下开发的
if (!function_exists('getVideoSecondsByUrlOrLocalPath')) {
    /**
     * getVideoSecondsByUrlOrLocalPath 根据文件url或本地路径获取视频时长
     *
     * @date     2021-05-25 10:48
     *
     * @param $url_or_local_path e.g:storage_path('app').'/2.mkv'
     * or eg:"https://cdn-staging.ivideocloud.cn/26/2/211/videos/1659/2ffkycsei6c_i3CUEPD07NTEdMk5.mp4"
     *
     * @return float 返回示例:10.172
     */
    function getVideoSecondsByUrlOrLocalPath($url_or_local_path)
    {
        if (!$url_or_local_path) {
            return null;
        }
        try {
            if (false !== filter_var($url_or_local_path, FILTER_VALIDATE_URL)) {
                // get duration by url
                if (!check_remote_file_exists($url_or_local_path)) {
                    return null;
                }
                // Copy remote file locally to scan with getID3()
                $remote_file_name = $url_or_local_path;
                if ($fp_remote = fopen($remote_file_name, 'rb')) {
                    $tmp_path = '/tmp';
                    if (!File::exists($tmp_path)) {
                        $tmp_path = storage_path('app').'/tmp';
                        if (!File::exists($tmp_path)) {
                            File::makeDirectory($tmp_path);
                        }
                    }
                    $local_temp_file_name = tempnam($tmp_path, 'getID3');
                    if ($fp_local = fopen($local_temp_file_name, 'wb')) {
                        while ($buffer = fread($fp_remote, 8192)) {
                            fwrite($fp_local, $buffer);
                        }
                        fclose($fp_local);
                        // Initialize getID3 engine
                        $getID3 = new \getID3();
                        $file_info = $getID3->analyze($local_temp_file_name);
                        // Delete temporary file
                        unlink($local_temp_file_name);
                    }
                    fclose($fp_remote);
                }

                $duration = $file_info['playtime_seconds'];
            } else {
                // get duration by local path
                if (false == File::exists($url_or_local_path)) {
                    return null;
                }
                $getID3 = new \getID3();
                $ThisFileInfo = $getID3->analyze($url_or_local_path);

                $duration = $ThisFileInfo['playtime_seconds'];
            }

            return (float) substr(sprintf('%.4f', $duration), 0, -1);
        } catch (Exception $e) {
            return null;
        }
    }
}

评论被关闭。