it编程 > 编程语言 > Php

PHP调用FFmpeg实现视频切片

47人参与 2025-04-24 Php

注:使用的视频为mp4,转换成.m3u8播放列表和.ts切片文件

1、安装ffmpeg

我这边是通过nux dextop仓库来安装ffmpeg。

(1) 安装epel仓库

sudo yum install -y epel-release

(2)下载并安装nux dextop仓库的rpm包

sudo rpm --import http://li.nux.ro/download/nux/rpm-gpg-key-nux.ro sudo rpm -uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm

(3)更新yum缓存

sudo yum update -y

(4) 安装ffmpeg

sudo yum install -y ffmpeg ffmpeg-devel

(5)验证安装

ffmpeg -version

2、安装php

sudo yum install php php-cli

验证安装

php -v

3、php脚本

<?php
// 设置输入视频文件、切片时长(秒)和输出目录
$videofile = '/data/video/input.mp4'; // 输入视频文件路径
$segmentduration = 10; // 切片时长,单位:秒
$outputdir = 'output'; // 输出目录
// 确保输出目录存在
if (!is_dir($outputdir)) {
    mkdir($outputdir, 0777, true);
}
// 构建并执行ffmpeg命令以生成.m3u8播放列表和.ts切片文件
// 使用'-strict -2'参数允许使用实验性编码器'aac'
$cmd = "ffmpeg -i " . escapeshellarg($videofile) .
       " -codec:v libx264 -codec:a aac -strict -2 -hls_time " . escapeshellarg($segmentduration) .
       " -hls_list_size 0 -hls_flags delete_segments " . escapeshellarg($outputdir . "/output.m3u8");
// 或者,如果您有 'libfdk_aac' 可用,可以替换 '-codec:a aac -strict -2' 为 '-codec:a libfdk_aac'
// $cmd = "ffmpeg -i " . escapeshellarg($videofile) .
//        " -codec:v libx264 -codec:a libfdk_aac -hls_time " . escapeshellarg($segmentduration) .
//        " -hls_list_size 0 -hls_flags delete_segments " . escapeshellarg($outputdir . "/output.m3u8");
shell_exec($cmd);
// 设置目标目录
$targetdir = 'target_dir';
if (!is_dir($targetdir)) {
    mkdir($targetdir, 0777, true);
}
// 检查.m3u8文件是否存在
$playlistfile = $outputdir . '/output.m3u8';
if(file_exists($playlistfile)){
    // 复制.m3u8播放列表文件
    copy($playlistfile, $targetdir . '/output.m3u8');
    // 获取所有.ts切片文件,并将其复制到目标目录
    $tsfiles = glob($outputdir . '/*.ts');
    foreach ($tsfiles as $tsfile) {
        copy($tsfile, $targetdir . '/' . basename($tsfile));
    }
    echo "视频切片及文件复制操作完成。\n";
} else {
    echo "ffmpeg处理失败,未找到输出文件。\n";
}
?>

4、创建目录(/data)

视频目录:/data/video

php脚本目录:/data  脚本名称:slice_video.php 

5、执行脚本

php slice_video.php

6、生成的切片文件夹

7、安装nginx

(1)安装

sudo yum install nginx -y

(2)启动 nginx

sudo systemctl start nginx
sudo systemctl enable nginx

(3) 检查 nginx 状态

sudo systemctl status nginx

(4)关闭防火墙

sudo systemctl stop firewalld
sudo systemctl disable firewalld
sudo systemctl status firewalld

(5)nginx.conf文件配置

文件位置:/etc/nginx/nginx.conf

sudo nginx -t  # 测试配置文件语法是否正确
sudo systemctl reload nginx  # 重新加载 nginx使配置生效
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
 
include /usr/share/nginx/modules/*.conf;
 
events {
    worker_connections 1024;
}
 
http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log  /var/log/nginx/access.log  main;
 
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;
 
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
 
    include /etc/nginx/conf.d/*.conf;
 
    server {
        listen 80;
        server_name 192.168.126.129;
 
        location /hls/ {
            alias /data/target_dir/; # 替换为你的实际目录路径
            types {
                application/vnd.apple.mpegurl m3u8;
                video/mp2t ts;
         }
            add_header 'cache-control' 'no-cache';
            add_header 'access-control-allow-origin' '*';
        }
    }
 
}

8、编写html播放器

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>hls stream player</title>
    <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
</head>
<body>
 
<h1>视频播放器</h1>
<video id="video" controls autoplay></video>
 
<script>
    if(hls.issupported()) {
        var video = document.getelementbyid('video');
        var hls = new hls();
        // 这里替换为你的.m3u8文件的实际url
        var url = 'http://192.168.126.129/hls/output.m3u8'; // 替换为你的实际url
        
        hls.loadsource(url);
        hls.attachmedia(video);
        hls.on(hls.events.manifest_parsed, function() {
            video.play();
        });
    } else if (video.canplaytype('application/vnd.apple.mpegurl')) {
        // 如果浏览器直接支持hls,则可以直接设置src
        video.src = 'http://192.168.126.129/hls/output.m3u8'; // 替换为你的实际url
        video.addeventlistener('loadedmetadata', function() {
            video.play();
        });
    }
</script>
 
</body>
</html>

到此这篇关于php调用ffmpeg实现视频切片的文章就介绍到这了,更多相关php ffmpeg视频切片内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

浅析PHP如何并行异步处理HTTP请求

04-24

PHP WindSearch实现站内搜索功能

04-24

php实现redis缓存配置和使用方法详解

04-24

PHP建立MySQL与MySQLi持久化连接(长连接)区别

04-24

使用PHP实现RESTful API的常见问题与解决方案

04-24

PHP如何使用XlsWriter实现百万级数据导入导出

04-24

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论