本文主要是介绍Java mp4转flv(基于javacv),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
依赖包
<dependency><groupId>org.bytedeco</groupId><artifactId>javacv</artifactId><version>1.4.3</version></dependency>
关键实现类
- FFmpegFrameGrabber:采集图像。从网络或者本地采集。
- FFmpegFrameRecorder:记录图像到你指定的文件或输出流
mp4网络地址转flv写入到响应
/*** mp4转flv,然后添加到响应* @param fileURL mp4的网络地址*/@SneakyThrowspublic static void convertMp4ToFlvAndWriteToResponse(String fileURL, HttpServletResponse response) {FFmpegFrameRecorder recorder = null;// 从网络上采集try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(new URL(fileURL).openStream())){grabber.start();int imageWidth = grabber.getImageWidth();int imageHeight = grabber.getImageHeight();// 记录器,图像记录结果写到响应流recorder = new FFmpegFrameRecorder(response.getOutputStream(), imageWidth, imageHeight);recorder.setInterleaved(true);recorder.setVideoBitrate(2500000);recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);recorder.setFormat("flv");recorder.setFrameRate(grabber.getFrameRate());recorder.setGopSize((int) (grabber.getFrameRate() * 2));recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);recorder.start();// 处理视频帧。(开始记录到响应流)Frame frame;while (true) {frame = grabber.grabFrame();if (frame == null) {break; // 没有更多帧}recorder.record(frame);}} catch (Exception e) {e.printStackTrace();} finally {// 确保资源被释放if (recorder != null) {recorder.stop();}}}
本地mp4转flv
@SneakyThrowspublic static void main(String[] args) {String inputFilePath = "C:\\Users\\admin\\Desktop\\a.mp4";String outputFilePath = "C:\\Users\\admin\\Desktop\\b.flv";FFmpegFrameRecorder recorder = null;try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFilePath)){grabber.start();int imageWidth = grabber.getImageWidth();int imageHeight = grabber.getImageHeight();recorder = new FFmpegFrameRecorder(outputFilePath, imageWidth, imageHeight);recorder.setInterleaved(true);recorder.setVideoBitrate(2500000);recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);recorder.setFormat("flv");recorder.setFrameRate(grabber.getFrameRate());recorder.setGopSize((int) (grabber.getFrameRate() * 2));recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);recorder.start();// 处理视频帧Frame frame;while (true) {frame = grabber.grabFrame();if (frame == null) {break; // 没有更多帧}recorder.record(frame);}} catch (Exception e) {e.printStackTrace();} finally {// 确保资源被释放if (recorder != null) {recorder.stop();}System.out.println("转换完成");}}
import(选看)
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacpp.avutil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
这篇关于Java mp4转flv(基于javacv)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!