使用java调用Ffmpeg转码

Java 视频转码(转为MPEG-4格式)

依赖

<dependency>
	<groupId>org.bytedeco</groupId>
	<artifactId>javacv</artifactId>
	<version>1.4.1</version>
</dependency>

<dependency>
	<groupId>org.bytedeco</groupId>
	<artifactId>javacpp</artifactId>
	<version>1.4.1</version>
</dependency>

<dependency>
	<groupId>org.bytedeco.javacpp-presets</groupId>
	<artifactId>opencv-platform</artifactId>
	<version>3.4.1-1.4.1</version>
</dependency>

<dependency>
	<groupId>org.bytedeco.javacpp-presets</groupId>
	<artifactId>ffmpeg-platform</artifactId>
	<version>3.4.2-1.4.1</version>
</dependency>

工具类

import org.bytedeco.javacv.Frame;
import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacv.FrameGrabber;
import org.bytedeco.javacv.FrameRecorder;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;

/**
 * 视频转码工具类
 */
public class VideoConvertUtil {
	
    public void convert(String inputFile, String outputFile) throws Exception {
        FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(inputFile);
        Frame captured_frame;
        FFmpegFrameRecorder recorder = null;

        try {
            grabber.start();

            recorder = new FFmpegFrameRecorder(outputFile, grabber.getImageWidth(), grabber.getImageHeight(), grabber.getAudioChannels());
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_MPEG4);
            recorder.setFormat("mp4");
            recorder.setFrameRate(grabber.getFrameRate());
			recorder.setSampleRate(grabber.getSampleRate());
			recorder.setVideoBitrate(grabber.getVideoBitrate());
			recorder.setAspectRatio(grabber.getAspectRatio());
			recorder.setAudioBitrate(grabber.getAudioBitrate());
			recorder.setAudioOptions(grabber.getAudioOptions());
            recorder.setAudioCodec(avcodec.AV_CODEC_ID_AAC);
            recorder.start();

            while (true) {
                captured_frame = grabber.grabFrame();
                if (captured_frame == null) {
                    System.out.println("转码完成");
                    break;
                }
                recorder.record(captured_frame);
            }

        } catch (FrameRecorder.Exception e) {
            e.printStackTrace();
        } finally {
            if (recorder != null) {
                try {
                    recorder.close();
                } catch (Exception e) {
                    System.out.println("recorder.close异常" + e);
                }
            }

            try {
                grabber.close();
            } catch (FrameGrabber.Exception e) {
                System.out.println("frameGrabber.close异常" + e);
            }
        }
    }
}

VideoConvertUtil convertUtil = new VideoConvertUtil();
convertUtil.convert(url, videoSavePath);

你可能感兴趣的:(ffmpeg,java,开发语言)