FFmpeg音视频处理解决方案

核心组件:

ffmpeg:主要的命令行工具,用于转码、转换格式等

ffprobe:用于分析多媒体文件信息的工具

ffplay:简单的媒体播放器

主要功能:

✅ 格式转换(转码)

✅ 视频裁剪、合并

✅ 调整分辨率、比特率

✅ 提取音频/视频

✅ 截图/生成缩略图

✅ 添加水印、字幕

✅ 流媒体处理

一、安装FFmpeg

Windows:

  1. 访问 https://ffmpeg.org/download.html
  2. 下载Windows版本,解压到指定目录
  3. 将bin目录添加到系统PATH环境变量

Linux (Ubuntu/Debian):

bash 复制代码
sudo apt update
sudo apt install ffmpeg

macOS:

bash 复制代码
brew install ffmpeg

二、项目配置

在application.properties或application.yml中配置FFmpeg路径:

properties 复制代码
# application.properties
ffmpeg.path=/usr/bin/ffmpeg  # Linux/Mac
# 或
ffmpeg.path=C:\\ffmpeg\\bin\\ffmpeg.exe  # Windows

三、依赖注入与异步处理

java 复制代码
@Service
@Slf4j
public class VideoTranscodingService {
    
    @Value("${ffmpeg.path}")
    private String ffmpegPath; // 注入FFmpeg路径
    
    @Async // 异步执行,避免阻塞请求
    public void transcodeVideo(Long materialId, String inputPath) {
        // 转码逻辑
    }
}

核心转码方法

  • ProcessBuilder
  • Process
java 复制代码
private void transcodeToResolution(String inputPath, String outputPath, String resolution) throws Exception {
    List<String> command = new ArrayList<>();
    command.add(ffmpegPath);
    command.add("-i");
    command.add(inputPath);    // 输入文件
    command.add("-s");
    command.add(resolution);   // 目标分辨率
    command.add("-c:v");
    command.add("libx264");    // 视频编码器
    command.add("-crf");
    command.add("23");         // 视频质量
    command.add("-c:a");
    command.add("aac");        // 音频编码器
    command.add("-b:a");
    command.add("128k");       // 音频比特率
    command.add(outputPath);   // 输出文件
    
    ProcessBuilder builder = new ProcessBuilder(command);
    Process process = builder.start();
    int exitCode = process.waitFor(); // 等待转码完成
    
    if (exitCode != 0) {
        throw new RuntimeException("FFmpeg转码失败,退出码: " + exitCode);
    }
}

四、控制器中上传文件视频

java 复制代码
@RestController
@RequestMapping("/api/video")
public class VideoController {
    
    @Autowired
    private VideoTranscodingService transcodingService;
    
    @PostMapping("/upload")
    public ResponseEntity<String> uploadVideo(@RequestParam("file") MultipartFile file, 
                                             @RequestParam Long materialId) {
        try {
            // 1. 保存上传的文件
            String uploadDir = "uploads/";
            String originalFilename = file.getOriginalFilename();
            String filePath = uploadDir + UUID.randomUUID() + "_" + originalFilename;
            
            File dest = new File(filePath);
            file.transferTo(dest);
            
            // 2. 异步启动转码
            transcodingService.transcodeVideo(materialId, filePath);
            
            return ResponseEntity.ok("视频上传成功,转码中...");
            
        } catch (Exception e) {
            return ResponseEntity.status(500).body("上传失败: " + e.getMessage());
        }
    }
}
java 复制代码
@GetMapping("/status/{materialId}")
public ResponseEntity<Map<String, Object>> getTranscodingStatus(@PathVariable Long materialId) {
    CourseMaterial material = materialRepository.findById(materialId).orElse(null);
    
    if (material == null) {
        return ResponseEntity.notFound().build();
    }
    
    Map<String, Object> response = new HashMap<>();
    response.put("status", material.getTranscodingStatus());
    response.put("filePath", material.getFilePath());
    response.put("duration", material.getDuration());
    
    return ResponseEntity.ok(response);
}
相关推荐
淡淡的香烟3 小时前
Android Camera开发详解
android·音视频
≮傷£≯√8 小时前
图片合并成视频 img2video ffmpeg
ffmpeg·音视频
A133455510 小时前
视频特效字幕怎么翻译?保姆级AI字幕与外挂字幕教程
人工智能·音视频
ViiTor_AI1 天前
从去字幕到 AI 配音:完整视频本地化流程
人工智能·音视频
明德扬1 天前
多路MIPI摄像头如何同步聚合?一文看懂FPGA视频汇聚方案
fpga开发·音视频
HY小宝F1 天前
树莓派 FFmpeg 实战笔记(二):命令行、源码编译与硬件编码的真相
学习·职场和发展·ffmpeg
折枝吖1 天前
音视频开发-PCM 原理与 AI 模块实战
音视频·pcm
HySpark1 天前
熙瑾·会悟 ASR 实战:Qwen-ASR 漏字导致转写不完整,如何从音频分段到二次校验解决?
音视频·熙瑾会悟
qq_316837751 天前
uniapp + Vite + ffmpeg-wasm 0.12.x 集成示例
ffmpeg·uni-app·wasm
qingmiaozhuan1 天前
电脑录屏黑屏?只有声音没画面?从原理到排查一篇搞定
ffmpeg·电脑·音视频开发·录屏技术·电脑录屏