JavaCV教程篇1之springboot调用ffmpeg将webm视频格式转换为MP4格式

准备环境:
springboot2.x
maven
1.第一步,在pom.xml文件中加入JavaCV依赖,如下:


            org.bytedeco
            javacv-platform
            1.5.4
 

2.编写如下函数:

import org.bytedeco.ffmpeg.global.avcodec;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.File;


  public  String convertToMp4(File file) {

        FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(file);
        String fileName = null;
        Frame captured_frame = null;
        FFmpegFrameRecorder recorder = null;
        try {
            frameGrabber.start();
            fileName = file.getAbsolutePath() + "__.mp4";
            recorder = new FFmpegFrameRecorder(fileName, frameGrabber.getImageWidth(), frameGrabber.getImageHeight(), frameGrabber.getAudioChannels());
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
            recorder.setFormat("mp4");
            recorder.setFrameRate(frameGrabber.getFrameRate());
            recorder.setSampleRate(frameGrabber.getSampleRate());

            recorder.setAudioChannels(frameGrabber.getAudioChannels());
            recorder.setFrameRate(frameGrabber.getFrameRate());
            recorder.start();
            while ((captured_frame = frameGrabber.grabFrame()) != null) {
                try {
                    recorder.record(captured_frame);
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
            recorder.stop();
            recorder.release();
            frameGrabber.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

3.调用转换函数,如下:

 void contextLoads() {
        String path="C:\\AAA\\BBB\\test1.webm";
        convertToMp4(new File(path));
    }

4.最后会在路径C:\AAA\BBB\ 下生成文件test1.webm.__mp4

你可能感兴趣的:(JavaCV教程篇1之springboot调用ffmpeg将webm视频格式转换为MP4格式)