Android MediaMuxer readSampleData IllegalStateException

时间:2014-10-20 10:48:54

标签: android illegalstateexception illegalargumentexception mediacodec mediamuxer

我使用以下代码生成视频。但是,每5次尝试中就有一次readSampleData会引发IllegalArgumentException或IllegalStateException。我该怎么做才能阻止例外。我可以在调用readSampleData之前检查提取器的状态。如果是这样,怎么样?

MediaExtractor videoExtractor = new MediaExtractor();
videoExtractor.setDataSource(SOURCE);

Log.d(TAG, "Video Extractor Track Count " + videoExtractor.getTrackCount() );

MediaMuxer muxer = new MediaMuxer(outputFile, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

videoExtractor.selectTrack(0);
MediaFormat videoFormat = videoExtractor.getTrackFormat(0);
int videoTrack = muxer.addTrack(videoFormat);

Log.d(TAG, "Video Format " + videoFormat.toString() );

boolean videoEnded = false;
long videoTimeStamp = 0;
int frameCount = 0;
int offset = 100;
ByteBuffer videoBuf = ByteBuffer.allocate(MAX_SAMPLE_SIZE);
BufferInfo videoBufferInfo = new BufferInfo();

muxer.start();

while (!videoEnded) 
{
    videoBufferInfo.offset = offset;
    videoBufferInfo.size = videoExtractor.readSampleData(videoBuf, offset);

    if (videoBufferInfo.size < 0) 
    {
        Log.d(TAG, "video ended " + videoBufferInfo.size);
        videoEnded = true;
        videoBufferInfo.size = 0;
    } 
    else 
    {
        videoTimeStamp = videoBufferInfo.presentationTimeUs = videoExtractor.getSampleTime();
        videoBufferInfo.flags = videoExtractor.getSampleFlags();
        muxer.writeSampleData(videoTrack, videoBuf, videoBufferInfo);
        videoExtractor.advance();
        frameCount++;
        Log.d(TAG, "Frame (" + frameCount + ") Video PresentationTimeUs:" + (videoBufferInfo.presentationTimeUs/1000000.0f)  +" Flags:" + videoBufferInfo.flags +" Size " + videoBufferInfo.size);
    }
}

muxer.stop();
muxer.release();

实际代码在视频提取器循环后为视频添加音频。

0 个答案:

没有答案