Steve M
Steve M

Reputation: 9784

Presentation time of samples quickly grows larger than total duration

I'm using MediaCodec to decode audio tracks. My decoding class works fine for playing the audio. I'm trying to show the progress of the track in a SeekBar, using the total track duration and the total played time. I have two longs, one which records the total duration of the track in microseconds, and another which records the total played time of the track in microseconds.

The problem I am having is the played duration quickly becomes larger than the total duration of the track. I don't understand where I'm going wrong.

long declarations in decoding class:

private long durationUs; //track duration in us
private volatile long currentTimeUs; //total played duration thus far

Determining the total duration in ctor:

extractor = new MediaExtractor();
extractor.setDataSource(fullPath);

format = extractor.getTrackFormat(0);
String mime = format.getString(MediaFormat.KEY_MIME);
durationUs = format.getLong(MediaFormat.KEY_DURATION);

Method where I add the time of the input sample to currentTimeUs:

private void advanceInput()
{
    boolean sawInputEOS = false;

    int inputBufIndex = codec.dequeueInputBuffer(TIMEOUT_US);
    if (inputBufIndex >= 0)
    {
        ByteBuffer dstBuf = codecInputBuffers[inputBufIndex];

        int sampleSize = extractor.readSampleData(dstBuf, 0);
        long presentationTimeUs = 0;

        if (sampleSize < 0)
        {
            sawInputEOS = true;
            sampleSize = 0;
        }
        else
        {
            presentationTimeUs = extractor.getSampleTime();
            currentTimeUs += presentationTimeUs;
        }

        codec.queueInputBuffer(inputBufIndex,
                0,
                sampleSize,
                presentationTimeUs,
                sawInputEOS ? MediaCodec.BUFFER_FLAG_END_OF_STREAM : 0);
        if (!sawInputEOS)
        {
            extractor.advance();
        }
    }
}

Upvotes: 1

Views: 1595

Answers (1)

Steve M
Steve M

Reputation: 9784

The time returned from getSampleTime() is a timestamp, so we must subtract this time from the previous time.

presentationTimeUs = extractor.getSampleTime();
currentTimeUs += presentationTimeUs - lastPresentationTime;
lastPresentationTime = presentationTimeUs;

Upvotes: 1

Related Questions