如何使用MediaCodec裁剪视频

5

我正在尝试使用MediaProjection API记录屏幕。我想修剪由媒体投影记录的视频。有没有一种方法可以在不使用第三方依赖项的情况下完成此操作?


你找到解决方案了吗? - Martin Mlostek
不确定MediaProjection会话的输出是什么,但MediaCodec是正确的选择。旅程从这里开始:https://dev59.com/5nrZa4cB1Zd3GeqPxghc - Endre Börcsök
@martynmlostekk 是的,我找到了一个。我会把它作为答案发布。 - mnagy
2个回答

15

经过大量搜索和查找,我找到了这段代码片段

  /**
 * @param srcPath  the path of source video file.
 * @param dstPath  the path of destination video file.
 * @param startMs  starting time in milliseconds for trimming. Set to
 *                 negative if starting from beginning.
 * @param endMs    end time for trimming in milliseconds. Set to negative if
 *                 no trimming at the end.
 * @param useAudio true if keep the audio track from the source.
 * @param useVideo true if keep the video track from the source.
 * @throws IOException
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static void genVideoUsingMuxer(String srcPath, String dstPath,
                                       int startMs, int endMs, boolean useAudio, boolean
                                                   useVideo)
        throws IOException {
    // Set up MediaExtractor to read from the source.
    MediaExtractor extractor = new MediaExtractor();
    extractor.setDataSource(srcPath);
    int trackCount = extractor.getTrackCount();
    // Set up MediaMuxer for the destination.
    MediaMuxer muxer;
    muxer = new MediaMuxer(dstPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
    // Set up the tracks and retrieve the max buffer size for selected
    // tracks.
    HashMap<Integer, Integer> indexMap = new HashMap<>(trackCount);
    int bufferSize = -1;
    for (int i = 0; i < trackCount; i++) {
        MediaFormat format = extractor.getTrackFormat(i);
        String mime = format.getString(MediaFormat.KEY_MIME);
        boolean selectCurrentTrack = false;
        if (mime.startsWith("audio/") && useAudio) {
            selectCurrentTrack = true;
        } else if (mime.startsWith("video/") && useVideo) {
            selectCurrentTrack = true;
        }
        if (selectCurrentTrack) {
            extractor.selectTrack(i);
            int dstIndex = muxer.addTrack(format);
            indexMap.put(i, dstIndex);
            if (format.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) {
                int newSize = format.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE);
                bufferSize = newSize > bufferSize ? newSize : bufferSize;
            }
        }
    }
    if (bufferSize < 0) {
        bufferSize = DEFAULT_BUFFER_SIZE;
    }
    // Set up the orientation and starting time for extractor.
    MediaMetadataRetriever retrieverSrc = new MediaMetadataRetriever();
    retrieverSrc.setDataSource(srcPath);
    String degreesString = retrieverSrc.extractMetadata(
            MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
    if (degreesString != null) {
        int degrees = Integer.parseInt(degreesString);
        if (degrees >= 0) {
            muxer.setOrientationHint(degrees);
        }
    }
    if (startMs > 0) {
        extractor.seekTo(startMs * 1000, MediaExtractor.SEEK_TO_CLOSEST_SYNC);
    }
    // Copy the samples from MediaExtractor to MediaMuxer. We will loop
    // for copying each sample and stop when we get to the end of the source
    // file or exceed the end time of the trimming.
    int offset = 0;
    int trackIndex = -1;
    ByteBuffer dstBuf = ByteBuffer.allocate(bufferSize);
    MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
    try {
        muxer.start();
        while (true) {
            bufferInfo.offset = offset;
            bufferInfo.size = extractor.readSampleData(dstBuf, offset);
            if (bufferInfo.size < 0) {
                InstabugSDKLogger.d(TAG, "Saw input EOS.");
                bufferInfo.size = 0;
                break;
            } else {
                bufferInfo.presentationTimeUs = extractor.getSampleTime();
                if (endMs > 0 && bufferInfo.presentationTimeUs > (endMs * 1000)) {
                    InstabugSDKLogger.d(TAG, "The current sample is over the trim end time.");
                    break;
                } else {
                    bufferInfo.flags = extractor.getSampleFlags();
                    trackIndex = extractor.getSampleTrackIndex();
                    muxer.writeSampleData(indexMap.get(trackIndex), dstBuf,
                            bufferInfo);
                    extractor.advance();
                }
            }
        }
        muxer.stop();

        //deleting the old file
        File file = new File(srcPath);
        file.delete();
    } catch (IllegalStateException e) {
        // Swallow the exception due to malformed source.
        InstabugSDKLogger.w(TAG, "The source video file is malformed");
    } finally {
        muxer.release();
    }
    return;
}

编辑:仅供参考,这段代码来源于Google的相册应用程序,允许剪辑视频,在名为“VideoUtils”的文件中:

https://android.googlesource.com/platform/packages/apps/Gallery2/+/634248d/src/com/android/gallery3d/app/VideoUtils.java

缺失的代码是:

private static final String LOGTAG = "VideoUtils";
private static final int DEFAULT_BUFFER_SIZE = 1 * 1024 * 1024;

1
根据这段代码,它只裁剪到关键帧,是吗?我们能否在关键帧之后向复用器提供任何样本数据,以便它可以从任何B帧开始? - vxh.viet
1
有没有使用Uri或InputStream而不是文件路径来实现它的方式?这似乎需要API 26以上的版本,对吧?我在这里询问了相关问题:stackoverflow.com/q/54503331/878126。 - android developer
尝试了你的代码片段。但是生成的视频在某些方面是损坏的。当我尝试播放输出时,会显示“无法播放视频文件”。 - dexter2019
@mnagy使用上述代码剪辑视频完美运行。但对于某些视频,会抛出MPEG4Writer错误:不支持除视频/音频/元数据之外的轨道(文本/3gpp-tt)。MPEG4Writer:不支持的mime类型“text/3gpp-tt”。 - Mano

0

我正在使用上述代码进行剪辑。该视频文件有3个轨道格式。

  1. {track-id=1, file-format=video/mp4, level=1024, mime=video/avc, frame-count=5427, profile=8, language=, display-width=810, csd-1=java.nio.HeapByteBuffer[pos=0 lim=8 cap=8], durationUs=181080900, display-height=1440, width=810, rotation-degrees=0, max-input-size=874801, frame-rate=30, height=1440, csd-0=java.nio.HeapByteBuffer[pos=0 lim=33 cap=33]}

  2. {max-bitrate=125588, sample-rate=44100, track-id=2, file-format=video/mp4, mime=audio/mp4a-latm, profile=2, bitrate=125588, language=, aac-profile=2, durationUs=181138866, aac-format-adif=0, channel-count=2, max-input-size=65538, csd-0=java.nio.HeapByteBuffer[pos=0 lim=2 cap=2]}

  3. {text-format-data=java.nio.HeapByteBuffer[pos=0 lim=56 cap=56], track-id=3, file-format=video/mp4, durationUs=179640000, mime=text/3gpp-tt, language=, max-input-size=65536}

所以我无法剪辑那个视频。它会抛出以下错误信息:

MPEG4Writer: 不支持除视频/音频/元数据之外的轨道(文本/3gpp-tt) MPEG4Writer: 不支持的 MIME 类型 'text/3gpp-tt'

但是我只是在剪辑视频文件。请有经验的人帮我解决这个问题。


你解决了吗? - Adnan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接