美文网首页
JavaCV 实现视频转码

JavaCV 实现视频转码

作者: oO白眉大虾Oo | 来源:发表于2020-05-22 21:32 被阅读0次

    查询了网上很多资料,发现没有比较靠谱的实现,JavaCV的资料还是比较少的

    安装依赖

    <dependency>
      <groupId>org.bytedeco</groupId>
      <artifactId>javacv-platform</artifactId>
      <version>1.5.3</version>
    </dependency>
    

    代码实现

        /**
         * 视频转码
         */
        public static void recode() throws FrameGrabber.Exception, FrameRecorder.Exception {
            String filePath = "ef568e9b96be750fba2e918b651aa70c.avi";
            String ext = filePath.substring(filePath.lastIndexOf("."));
            String newFilePath = filePath.replace(ext, "_recode.mp4");
            FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(filePath);
            grabber.start();
            FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(newFilePath, grabber.getImageWidth(),
                grabber.getImageHeight(), grabber.getAudioChannels());
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264);
            recorder.setFormat("mp4");
            recorder.setPixelFormat(avutil.AV_PIX_FMT_YUV420P);
            recorder.setFrameRate(grabber.getFrameRate());
            int bitrate = grabber.getVideoBitrate();
            if (bitrate == 0) {
                bitrate = grabber.getAudioBitrate();
            }
            recorder.setVideoBitrate(bitrate);
            recorder.start(grabber.getFormatContext());
            AVPacket packet;
            long dts = 0;
            while ((packet = grabber.grabPacket()) != null) {
                long currentDts = packet.dts();
                if (currentDts >= dts) {
                    recorder.recordPacket(packet);
                }
                dts = currentDts;
            }
            recorder.stop();
            recorder.release();
            grabber.stop();
        }
    

    相关文章

      网友评论

          本文标题:JavaCV 实现视频转码

          本文链接:https://www.haomeiwen.com/subject/oyncahtx.html