当前位置: 首页 > 工具软件 > MPEG Recorder > 使用案例 >

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

蔡鹏程
2023-12-01

问题:原视频的编码格式为H265,在小程序上面无法播放,需要转为MPEG-4格式。

1、引入相关依赖

<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>

2、视频转码工具类

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);
            }
        }
    }
}

3、调用工具类方法

VideoConvertUtil convertUtil = new VideoConvertUtil();
convertUtil.convert(url, videoSavePath);
 类似资料: