使用FFmpeg将视屏剪辑并上传到华为服务器上

使用FFmpeg将视屏剪辑并上传到华为服务器上

注意需要自己在windows上安装好FFmpeg组件
教程地址:https://www.jianshu.com/p/2b609afb9800
这套代码不管在linux还是windows系统上都能使用
linux上剪辑视屏也是需要进行组件的安装:https://blog.csdn.net/L1569850979/article/details/123269527?spm=1001.2014.3001.5501
上代码
导包

	<!--视屏剪辑-->
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>30.1.1-jre</version>
		</dependency>

		<dependency>
			<groupId>org.bytedeco</groupId>
			<artifactId>ffmpeg-platform</artifactId>
			<version>4.4-1.5.6</version>
		</dependency>

返回实体

import io.swagger.annotations.ApiModel;
import lombok.Data;

import java.io.Serializable;

/**
 * @author lilinchun
 * @date 2022/3/2 0002 11:45
 */
@Data
@ApiModel
public class FileVideoVO implements Serializable {


    /**
     * 原视频url
     */
    private String url;

    /**
     * 截取视屏url
     */
    private String cutUrl;

    /**
     * 文件名称
     */
    private String objectname;


}

主要代码

    /**
     * 
     * @param file 视屏原文件
     * @param start 剪辑开始位置
     * @param end 剪辑结束位置
     * @return
     * @throws Exception
     */
@Override
    public FileVideoVO videoUpload(MultipartFile file, String start, String end) throws Exception {
        FileVideoVO fileVideoVO = new FileVideoVO();
        ObsClient obsClient = new ObsClient(ak, sk, endPoint);
        //判断文件格式
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        // 判断文件格式
        switch (fileType) {
            case OssFormat.MP3:
                break;
            case OssFormat.MP4:
                break;
            default:
                throw new BusinessException(ErrorCode.FORMAT_ERROR.getCode(), ErrorCode.FORMAT_ERROR.getMsg());
        }
        InputStream inputStreamOld=file.getInputStream();
        //源文件上传
        PutObjectResult putObjectResultold = obsClient.putObject("bks", "clipFile/" + fileName, inputStreamOld);
        fileVideoVO.setUrl(putObjectResultold.getObjectUrl());
        //剪辑文件上传
        File file1 = TransferToFile.multipartFileToFile(file);
        log.info("文件字符串位置------------------:" + file1.getAbsolutePath());
        String str;
        if (file1.getAbsolutePath().lastIndexOf("\\") > 0) {
            str = file1.getAbsolutePath().substring(0, file1.getAbsolutePath().lastIndexOf("\\") + 1);
        } else {
            str = file1.getAbsolutePath().substring(0, file1.getAbsolutePath().lastIndexOf("/") + 1);
        }
        log.info("后传递路径-----------:" + str);
        str = new String(str.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
        String filPath = FfmpegUtil.cutOutVideo(file1, str, start, end);
        InputStream inputStream=getInputStream(filPath);
        //将剪辑文件上传到华为云服务器上
        PutObjectResult putObjectResult = obsClient.putObject("bks", "clipFile/" + IdUtil.simpleUUID() + fileType, inputStream);
        inputStreamOld.close();
        inputStream.close();
        TransferToFile.deleteTempFile(file1);
        fileVideoVO.setCutUrl(putObjectResult.getObjectUrl());
        obsClient.close();
        //删除临时文件
        FfmpegUtil.deleteFilePlace(FfmpegUtil.sortOut(filPath));
        return fileVideoVO;
    }
      //读取临时文件
    public InputStream getInputStream(String resultPath) throws Exception {

        Thread.sleep(3000);
        FileInputStream  fis = new FileInputStream(resultPath);
        int available = fis.available();
        log.info("外流的大小----------:" + available);
        if(available==0) {
            int i = 10;
            while (i > 1) {
                log.info("流的大小----------:" + available);
                if (available == 0) {
                    fis.close();
                    i--;
                    //睡三秒
                    Thread.sleep(3000);
                } else {
                    i = 0;
                }
                fis.close();
                fis = new FileInputStream(resultPath);
                available = fis.available();
            }
        }
        if (available == 0) {
            log.info("文件截取失败---------");
            throw new BusinessException(ErrorCode.CUT_ERROR.getCode(), ErrorCode.CUT_ERROR.getMsg());
        }
        return fis;

    }

几个工具类

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author lilinchun
 * @date 2022/3/1 0001 16:26
 */
public class TransferToFile {



    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * MultipartFile 转 File
     *
     * @param file
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }


    /**
     * 删除本地临时文件
     * @param file
     */
    public static void deleteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

}

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.base.Joiner;
import com.llcbk.error.BusinessException;
import com.llcbk.error.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacpp.Loader;


import java.io.*;
import java.util.Arrays;


/**
 * @author lilinchun
 * @date 2022/3/1 0001 16:11
 */
@Slf4j
public class FfmpegUtil {



    /**
     * 视频裁剪
     *
     * @param file 视频 文件
     * @param outputDir 临时目录
     * @throws Exception 异常
     *
     * star 开始位置
     * end 其实位置
     * -i 读取源文件
     * -ss 文件开始位置
     * -to 文件结束文职
     * -b  设置比特率
     * -y 表示输出文件,如果已存在则覆盖
     * -vcodec copy 使用跟原视频相同的视频编解码器
     * -acodec copy 使用跟原视频相同的音频编解码器
     */
    public static String cutOutVideo(File file, String outputDir,String start,String end) throws Exception {
        String videoPath ;
        try {
            videoPath = file.getAbsolutePath();
        } catch (Exception e) {
            log.info("错误----------:" + e.getMessage());
            throw new BusinessException(ErrorCode.CUT_ERROR.getCode(),ErrorCode.CUT_ERROR.getMsg());
        }
        String resultPath =
                Joiner.on(File.separator).join(Arrays.asList(outputDir, IdUtil.simpleUUID() + "." + "mp4"));
        ProcessBuilder builder =
                new ProcessBuilder(
                        "ffmpeg",
                        "-i",
                        videoPath,
                       "-ss",
                        start,
                        "-to",
                        end,
                        "-c",
                        "copy",
                        "-y",
                        resultPath);
        builder.inheritIO().start();
        return resultPath;

    }

    /**
     * 视频裁剪
     *
     * @param file 视频 文件
     * @param outputDir 临时目录
     * @throws Exception 异常
     *
     * -i 读取源文件
     * -ss 文件开始位置
     * -to 文件结束文职
     * -b  设置比特率
     * -y 表示输出文件,如果已存在则覆盖
     * -vcodec copy 使用跟原视频相同的视频编解码器
     * -acodec copy 使用跟原视频相同的音频编解码器
     */
    public static String cutOutVideoOld(File file, String outputDir,String star,String end) throws Exception {
        String videoPath = null;
        try {
            videoPath = file.getAbsolutePath();
        } catch (Exception e) {
            log.info("错误----------:" + e.getMessage());
            throw new BusinessException(ErrorCode.CUT_ERROR.getCode(),ErrorCode.CUT_ERROR.getMsg());
        }
        String resultPath =outputDir+IdUtil.simpleUUID()+"."+"mp4";
        String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class);
        ProcessBuilder builder =
                new ProcessBuilder(
                        ffmpeg,
                        "-i",
                        videoPath,
                        "-codec",
                        "copy",
                        "-ss",
                        star,
                        "-to",
                        end,
                        "-b",
                        "2000k",
                        "-y",
                        "-threads",
                        "5",
                        "-preset",
                        "ultrafast",
                        "-strict",
                        "-2",
                        resultPath);

        builder.inheritIO().start();
        return resultPath;

    }


    /**
     * 删除本地临时文件
     * @param path
     */
    public static void deleteFilePlace(String path) {
        System.out.println("path----------------:"+path);
        File file = new File(path);
        File del = new File(file.toURI());
        System.out.println("删除本地临时文件-------"+del.delete());
    }
    /**
     * 整理路径
     */
    public static String sortOut(String path){
        if(StringUtils.isNotBlank(path)){
            char[] c = path.toCharArray();
            String strNew ="";
            for (int i = 0; i < c.length; i++) {
                if (c[i] == '\\'&&c[i]==c[i+1]) {
                    continue;
                }
                strNew=strNew+c[i];
            }
            return strNew;
        }else {
            return path;
        }
    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
最新全套Jar: FFMPEG3.4.1+JavaCV1.4.1+OpenCV3.4.1-含windows&linux;平台链接库。安卓和macos的链接库将另发。 请根据平台选择适当的链接库。 artoolkitplus-linux-armhf.jar artoolkitplus-linux-ppc64le.jar artoolkitplus-linux-x86.jar artoolkitplus-linux-x86_64.jar artoolkitplus-platform.jar artoolkitplus-windows-x86.jar artoolkitplus-windows-x86_64.jar artoolkitplus.jar ffmpeg-linux-armhf.jar ffmpeg-linux-ppc64le.jar ffmpeg-linux-x86.jar ffmpeg-linux-x86_64.jar ffmpeg-platform.jar ffmpeg-windows-x86.jar ffmpeg-windows-x86_64.jar ffmpeg.jar flandmark-linux-armhf.jar flandmark-linux-ppc64le.jar flandmark-linux-x86.jar flandmark-linux-x86_64.jar flandmark-platform.jar flandmark-windows-x86.jar flandmark-windows-x86_64.jar flandmark.jar flycapture-linux-armhf.jar flycapture-linux-x86.jar flycapture-linux-x86_64.jar flycapture-platform.jar flycapture-windows-x86.jar flycapture-windows-x86_64.jar flycapture.jar javacpp.jar javacv-platform.jar javacv.jar libdc1394-linux-armhf.jar libdc1394-linux-ppc64le.jar libdc1394-linux-x86.jar libdc1394-linux-x86_64.jar libdc1394-platform.jar libdc1394-windows-x86.jar libdc1394-windows-x86_64.jar libdc1394.jar libfreenect-linux-armhf.jar libfreenect-linux-ppc64le.jar libfreenect-linux-x86.jar libfreenect-linux-x86_64.jar libfreenect-platform.jar libfreenect-windows-x86.jar libfreenect-windows-x86_64.jar libfreenect.jar libfreenect2-linux-x86.jar libfreenect2-linux-x86_64.jar libfreenect2-platform.jar libfreenect2-windows-x86_64.jar libfreenect2.jar librealsense-linux-x86.jar librealsense-linux-x86_64.jar librealsense-platform.jar librealsense-windows-x86.jar librealsense-windows-x86_64.jar librealsense.jar opencv-ios-arm64.jar opencv-ios-x86_64.jar opencv-linux-armhf.jar opencv-linux-ppc64le.jar opencv-linux-x86.jar opencv-linux-x86_64.jar opencv-platform.jar opencv-windows-x86.jar opencv-windows-x86_64.jar opencv.jar videoinput-platform.jar videoinput-windows-x86.jar videoinput-windows-x86_64.jar videoinput.jar

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱上编程2705

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值