Spring Boot 3整合FFmpeg进行图片和MP3转换为视频

Spring Boot 3整合FFmpeg进行图片和MP3转换为视频的示例代码如下:

添加FFmpeg依赖到pom.xml:

bash 复制代码
<dependency>
    <groupId>com.github.kokorin.jaffree</groupId>
    <artifactId>jaffree</artifactId>
    <version>0.1.2</version>
</dependency>

创建一个服务类来执行转换:

bash 复制代码
import com.github.kokorin.jaffree.ffmpeg.FFmpeg;
import com.github.kokorin.jaffree.ffmpeg.FFmpegResult;
import org.springframework.stereotype.Service;
 
import java.nio.file.Paths;
 
@Service
public class VideoConversionService {
 
    public void convertImageAndAudioToVideo(String imagePath, String audioPath, String outputPath) throws Exception {
        FFmpegResult result = FFmpeg.atPath()
                .addInput(FFmpeg.input(imagePath))
                .addInput(FFmpeg.input(audioPath))
                .overrideOutputFiles(true)
                .addOutput(FFmpeg.output(outputPath)
                        .videoCodec("copy")
                        .audioCodec("copy"))
                .execute();
 
        if (result.getState() == FFmpegResult.State.SUCCESS) {
            System.out.println("转换成功");
        } else {
            System.out.println("转换失败");
        }
    }
}

在Spring Boot应用的主类或者任意一个配置类中,调用转换服务:

bash 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
 
@Component
public class VideoConversionRunner implements CommandLineRunner {
 
    @Autowired
    private VideoConversionService videoConversionService;
 
    @Override
    public void run(String... args) throws Exception {
        String imagePath = "path/to/image.jpg";
        String audioPath = "path/to/audio.mp3";
        String outputPath = "path/to/output.mp4";
 
        videoConversionService.convertImageAndAudioToVideo(imagePath, audioPath, outputPath);
    }
}

确保你的图片和音频文件路径是正确的,并且FFmpeg可执行文件在你的系统PATH中或者通过FFmpeg.atPath()指定。

以上代码假设你已经有了一个运行中的Spring Boot 3应用,并且FFmpeg已经安装在你的系统上。如果FFmpeg没有安装,你需要先下载并安装FFmpeg,或者使用Docker容器等方式来运行它。

相关推荐
库库林_沙琪马24 分钟前
1、Hi~ SpringBoot
java·spring boot·后端
阿宁又菜又爱玩30 分钟前
Web后端开发入门
java·spring boot·后端·web
_院长大人_1 小时前
Spring Boot 客户端设计示例:自动刷新 Token 并重试接口调用(Springboot Starter 封装)
java·spring boot·后端
卷到起飞的数分1 小时前
19.Spring Boot原理1
java·spring boot·后端
鹿里噜哩1 小时前
Spring Authorization Server 打造认证中心(二)自定义数据库表
spring boot·后端·kotlin
v***87041 小时前
Spring Boot实现多数据源连接和切换
spring boot·后端·oracle
毕设源码-郭学长1 小时前
【开题答辩全过程】以 高校教室管理系统为例,包含答辩的问题和答案
java·spring boot
老华带你飞2 小时前
房屋租赁管理|基于springboot + vue房屋租赁管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·毕设
ACP广源盛139246256732 小时前
GSV2202D@ACP#DisplayPort 1.4 到 HDMI 2.0 转换器(带嵌入式 MCU)
单片机·嵌入式硬件·计算机外设·音视频
你好音视频2 小时前
RTSP拉流:RTP包解析流程详解
ffmpeg·音视频