当前位置: 首页 > article >正文

laravel项目中使用FFMPeg 剪裁视频

# 运行环境需安装的软件
ffmpeg

# 安装的扩展
pbmedia/laravel-ffmpeg: ^8.3

# 扩展文档 https://packagist.org/packages/pbmedia/laravel-ffmpeg

# 引入的类
use FFMpeg\Coordinate\TimeCode;
use FFMpeg\Format\Video\X264;
use FFMpeg\Exception\RuntimeException;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use ProtoneMedia\LaravelFFMpeg\Support\FFMpeg;


# 处理方法
    public function cutUrlVideo($ossVideoPath)
    {

        $maxDuration = env('CLIP_VIDEO_SECONDS'); // 需要的时长

        // 原始视频在 OSS 中的路径
        $ossVideoPath  = 'uploads/resource/2025/02/27/HzFdjwYQwUehk2WChH1DHAroKXMo0EkrG2lh1gQp.mp4';

        // 生成本地临时文件路径
        $tempInputPath = 'temp/input_' . uniqid() . '.mp4';
        $tempOutputPath = 'temp/output_' . uniqid() . '.mp4';

        // 将 OSS 视频下载到本地临时文件
        Storage::disk('public')->put($tempInputPath, Storage::disk('oss')->get($ossVideoPath));

        try {
            // 获取下载到本地的媒体对象
            $media = FFMpeg::fromDisk('public')->open($tempInputPath);

            // 获取视频总时长(秒)
            $duration = $media->getDurationInSeconds();

            // 根据时长判断处理逻辑
            if ($duration > $maxDuration) {
                $start = TimeCode::fromSeconds(0);
                $end = TimeCode::fromSeconds($maxDuration);
                $clipFilter = new \FFMpeg\Filters\Video\ClipFilter($start, $end);

                $media->addFilter($clipFilter)
                    ->export()
                    ->toDisk('public')
                    ->inFormat(new X264)
                    ->save($tempOutputPath);

                // 生成最终要使用的文件路径
                $folderName = "/uploads/resource/" . date("Y/m/d");
                $extension = pathinfo(basename($ossVideoPath), PATHINFO_EXTENSION);
                $newFilename = Str::uuid()->toString() . '.' . $extension;
                // 上传到 OSS
                $ossPath = "{$folderName}/{$newFilename}";
                Storage::disk('oss')->put($ossPath, Storage::disk('public')->get($tempOutputPath));

                return $ossPath;
            } else {
                return $ossVideoPath;
            }

        } finally {
            // 清理临时文件
            Storage::disk('public')->delete([$tempInputPath, $tempOutputPath]);
        }
    }


http://www.kler.cn/a/584745.html

相关文章:

  • Pytortch深度学习网络框架库 torch.no_grad方法 核心原理与使用场景
  • 重生之我在学Vue--第11天 Vue 3 高级特性
  • 版本控制泄露源码 .git
  • Vue.js 3 的设计思路:从声明式UI到高效渲染机制
  • LINUX 指令大全
  • ES6 Class 转 ES5 实现
  • 基于JSP和SQL的CD销售管理系统(源码+lw+部署文档+讲解),源码可白嫖!
  • 基于深度学习的多模态人脸情绪识别研究与实现(视频+图像+语音)
  • PyTorch深度学习框架60天进阶学习计划 - 第18天:模型压缩技术
  • Jenkins实现自动化构建与部署:上手攻略
  • 【SpringBoot】深入剖析 Spring Boot 启动过程(附源码与实战)
  • 【Leetcode 每日一题】3306. 元音辅音字符串计数 II
  • 【每日学点HarmonyOS Next知识】防截屏、加载不同View、函数传参、加载中效果、沉浸式底部状态栏
  • Unity中WolrdSpace下的UI展示在上层
  • 【redis】lua脚本
  • C#中继承的核心定义‌
  • SQL语言的系统运维
  • springboot436-基于SpringBoot的汽车票网上预订系统(源码+数据库+纯前后端分离+部署讲解等)
  • 缓存及其问题解决
  • centos没有ll