This sample shows how to use the MediaCoder to decode a video,
use a TimeAnimator to sync the rendering commands with the system
display frame rendering and finally render it to a TextureView.
MediaCodec was introduced in API 16, and can be used for low level (decoding/encoding) operations.
In the same API was also introduced TimeAnimator, which can be used to synchronise animation frames.
Finally, MediaExtractor provides a simple way to extract demuxed media data from a data source.
The main steps are described below:
new MediaExtractor()
and a TimeAnimator instance withnew TimeAnimator()
.setDataSource(this, videoUri, null)
on your MediaExtractor instance,videoUri
is the URI of your video source.getTrackCount()
to know how many tracks you have in your streams.unselectTrack(i)
where i
isgetTrackFormat(i).getString(MediaFormat.KEY_MIME)
i
is the index of your selected track.selectTrack(i)
MediaCodec.createDecoderByType(mimeType)
.configure(trackFormat, textureView, null, 0)
,trackFormat
is obtained by calling getTrackFormat(i)
on your MediaExtractor instance.onTimeUpdate(final TimeAnimator animation, final long totalTime, final long deltaTime)
method.onTimeUpdate
, check if the media track has reached the end of stream, using getSampleFlags()
MediaCodec.BUFFER_FLAG_END_OF_STREAM
flag.onTimeUpdate
, assuming this isn't the end of the sample, write the media sample to yourqueueInputBuffer(index, 0, size, presentationTimeUs, flags)
method.advance()
on yourdequeueOutputBuffer(info, timeout)
and releaseOutputBuffer(i, true)
, refer to MediaCodeconPause()
or if you have reached the end of the stream, call end()
on your TimeAnimation instance,stop()
and release()
on your MediaCodec instance, and finally, call release()
on your
This sample uses the Gradle build system. To build this project, use the
"gradlew build" command or use "Import Project" in Android Studio.
If you've found an error in this sample, please file an issue:
https://github.com/googlesamples/android-BasicMediaDecoder
Patches are encouraged, and may be submitted by forking this project and
submitting a pull request through GitHub. Please see CONTRIBUTING.md for more details.
Copyright 2019 The Android Open Source Project, Inc.
Licensed to the Apache Software Foundation (ASF) under one or more contributor
license agreements. See the NOTICE file distributed with this work for
additional information regarding copyright ownership. The ASF licenses this
file to you under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy of
the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.