Android 如何使用MediaCodec修剪视频

Android 如何使用MediaCodec修剪视频,android,mediamuxer,android-mediaprojection,android-mediacodec,Android,Mediamuxer,Android Mediaprojection,Android Mediacodec,我正在尝试用MediaProjectionAPI录制屏幕。我想修剪媒体投影录制的视频。有没有一种不使用任何第三方依赖关系的方法 经过大量挖掘,我找到了这个片段 /** * @param srcPath the path of source video file. * @param dstPath the path of destination video file. * @param startMs starting time in milliseconds for trimmi

我正在尝试用MediaProjectionAPI录制屏幕。我想修剪媒体投影录制的视频。有没有一种不使用任何第三方依赖关系的方法

经过大量挖掘,我找到了这个片段

  /**
 * @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;
}

我用上面的代码修剪。视频文件有3种轨迹格式

  • {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.heapbytbuffer[pos=0 lim=8 cap=8],durationUs=181080900,display height=1440,width=810,旋转度=0,最大输入大小=874801,帧速率=30,高度=1440,csd-0=java.nio.heapbytbuffer=8[pos=0 lim=33 cap=33]}

  • {最大比特率=125588,采样率=44100,曲目id=2,文件格式=video/mp4,mime=audio/mp4a latm,配置文件=2,比特率=125588,语言=,aac配置文件=2,持续时间=181138866,aac格式adif=0,频道计数=2,最大输入大小=65538,csd-0=java.nio.HeapByteBuffer[pos=0 lim=2 cap=2]}

  • {text format data=java.nio.HeapByteBuffer[pos=0 lim=56 cap=56],曲目id=3,文件格式=video/mp4,durationUs=179640000,mime=text/3gpp tt,语言=,最大输入大小=65536}

  • 所以我不能剪辑那个视频,它会 MPEG4Writer:不支持视频/音频/元数据以外的曲目(文本/3gpp tt) MPEG4Writer:不支持的mime“text/3gpp tt”


    但我只是在整理视频文件。请任何人解决我的问题

    你找到解决方案了吗?不确定MediaProjection会话的输出是什么,但MediaCodec是一条路。旅程从这里开始:@martynmlostekk是的,我找到了一个。我会把它作为答案发布基于这个片段,它只会修剪到关键帧,不是吗?我们能把它反馈给在关键帧之后对任何样本数据进行muxer,以便它可以从任何B帧开始?是否可以使用Uri或InputStream而不是文件路径进行此操作?似乎您可能需要API 26来完成此操作,对吗?我在这里询问了此问题:stackoverflow.com/q/54503331/878126尝试了您的片段。但是创建的视频在某种程度上已损坏。表示“无法播放视频文件”“当我试着玩游戏的时候output@mnagy使用上述代码剪裁视频效果非常好。某些视频的Bt抛出MPEG4Writer:Track(text/3gpp tt)而不是video/audio/metadata不受支持MPEG4Writer:Unsupported mime“text/3gpp tt”。
    private static final String LOGTAG = "VideoUtils";
    private static final int DEFAULT_BUFFER_SIZE = 1 * 1024 * 1024;