Most visited

Recently visited

Added in API level 18

MediaMuxer

public final class MediaMuxer
extends Object

java.lang.Object
   ↳ android.media.MediaMuxer


MediaMuxer facilitates muxing elementary streams. Currently supports mp4 or webm file as the output and at most one audio and/or one video elementary stream. MediaMuxer does not support muxing B-frames.

It is generally used like this:

 MediaMuxer muxer = new MediaMuxer("temp.mp4", OutputFormat.MUXER_OUTPUT_MPEG_4);
 // More often, the MediaFormat will be retrieved from MediaCodec.getOutputFormat()
 // or MediaExtractor.getTrackFormat().
 MediaFormat audioFormat = new MediaFormat(...);
 MediaFormat videoFormat = new MediaFormat(...);
 int audioTrackIndex = muxer.addTrack(audioFormat);
 int videoTrackIndex = muxer.addTrack(videoFormat);
 ByteBuffer inputBuffer = ByteBuffer.allocate(bufferSize);
 boolean finished = false;
 BufferInfo bufferInfo = new BufferInfo();

 muxer.start();
 while(!finished) {
   // getInputBuffer() will fill the inputBuffer with one frame of encoded
   // sample from either MediaCodec or MediaExtractor, set isAudioSample to
   // true when the sample is audio data, set up all the fields of bufferInfo,
   // and return true if there are no more samples.
   finished = getInputBuffer(inputBuffer, isAudioSample, bufferInfo);
   if (!finished) {
     int currentTrackIndex = isAudioSample ? audioTrackIndex : videoTrackIndex;
     muxer.writeSampleData(currentTrackIndex, inputBuffer, bufferInfo);
   }
 };
 muxer.stop();
 muxer.release();
 

Summary

Nested classes

class MediaMuxer.OutputFormat

Defines the output format. 

Public constructors

MediaMuxer(String path, int format)

Constructor.

Public methods

int addTrack(MediaFormat format)

Adds a track with the specified format.

void release()

Make sure you call this when you're done to free up any resources instead of relying on the garbage collector to do this for you at some point in the future.

void setLocation(float latitude, float longitude)

Set and store the geodata (latitude and longitude) in the output file.

void setOrientationHint(int degrees)

Sets the orientation hint for output video playback.

void start()

Starts the muxer.

void stop()

Stops the muxer.

void writeSampleData(int trackIndex, ByteBuffer byteBuf, MediaCodec.BufferInfo bufferInfo)

Writes an encoded sample into the muxer.

Protected methods

void finalize()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.

Inherited methods

From class java.lang.Object

Public constructors

MediaMuxer

Added in API level 18
MediaMuxer (String path, 
                int format)

Constructor. Creates a media muxer that writes to the specified path.

Parameters
path String: The path of the output media file.
format int: The format of the output media file.
Throws
IllegalArgumentException if path is invalid or format is not supported.
IOException if failed to open the file for write.

See also:

Public methods

addTrack

Added in API level 18
int addTrack (MediaFormat format)

Adds a track with the specified format.

The following table summarizes support for specific format keys across android releases. Keys marked with '+:' are required.

OS Version(s) MediaFormat keys used for
All Tracks Audio Tracks Video Tracks
JELLY_BEAN_MR2 +: KEY_MIME +: KEY_SAMPLE_RATE,
+: KEY_CHANNEL_COUNT,
+: codec-specific dataAAC
+: KEY_WIDTH,
+: KEY_HEIGHT,
no KEY_ROTATION, use setOrientationHint().mp4,
+: codec-specific dataAVC, MPEG4
KITKAT
KITKAT_WATCH
LOLLIPOP as above, plus
+: codec-specific dataVorbis & .webm
LOLLIPOP_MR1
M as above, plus
KEY_BIT_RATEAAC
N as above, plus
KEY_BIT_RATEMPEG4,
KEY_HDR_STATIC_INFO#, .webm,
KEY_COLOR_STANDARD#,
KEY_COLOR_TRANSFER#,
KEY_COLOR_RANGE#,
+: codec-specific dataHEVC,
codec-specific dataVP9

Notes:
#: storing into container metadata.
.mp4, .webm…: for listed containers
MPEG4, AAC…: for listed codecs

Note that the codec-specific data for the track must be specified using this method. Furthermore, codec-specific data must not be passed/specified via the writeSampleData() call.

The following table summarizes codec support for containers across android releases:

OS Version(s) Codec support
MP4 WEBM
JELLY_BEAN_MR2 AAC,
NB-AMR,
WB-AMR,
H.263,
MPEG-4,
AVC (H.264)
Not supported
KITKAT
KITKAT_WATCH
LOLLIPOP Vorbis,
VP8
LOLLIPOP_MR1
M
N as above, plus
HEVC (H.265)
as above, plus
VP9

Parameters
format MediaFormat: The media format for the track. This must not be an empty MediaFormat.
Returns
int The track index for this newly added track, and it should be used in the writeSampleData(int, ByteBuffer, MediaCodec.BufferInfo).
Throws
IllegalArgumentException if format is invalid.
IllegalStateException if muxer is in the wrong state.

release

Added in API level 18
void release ()

Make sure you call this when you're done to free up any resources instead of relying on the garbage collector to do this for you at some point in the future.

setLocation

Added in API level 19
void setLocation (float latitude, 
                float longitude)

Set and store the geodata (latitude and longitude) in the output file. This method should be called before start(). The geodata is stored in udta box if the output format is MUXER_OUTPUT_MPEG_4, and is ignored for other output formats. The geodata is stored according to ISO-6709 standard.

Parameters
latitude float: Latitude in degrees. Its value must be in the range [-90, 90].
longitude float: Longitude in degrees. Its value must be in the range [-180, 180].
Throws
IllegalArgumentException If the given latitude or longitude is out of range.
IllegalStateException If this method is called after start().

setOrientationHint

Added in API level 18
void setOrientationHint (int degrees)

Sets the orientation hint for output video playback.

This method should be called before start(). Calling this method will not rotate the video frame when muxer is generating the file, but add a composition matrix containing the rotation angle in the output video if the output format is MUXER_OUTPUT_MPEG_4 so that a video player can choose the proper orientation for playback. Note that some video players may choose to ignore the composition matrix in a video during playback. By default, the rotation degree is 0.

Parameters
degrees int: the angle to be rotated clockwise in degrees. The supported angles are 0, 90, 180, and 270 degrees.
Throws
IllegalArgumentException if degree is not supported.
IllegalStateException If this method is called after start().

start

Added in API level 18
void start ()

Starts the muxer.

Make sure this is called after addTrack(MediaFormat) and before writeSampleData(int, ByteBuffer, MediaCodec.BufferInfo).

Throws
IllegalStateException If this method is called after start() or Muxer is released

stop

Added in API level 18
void stop ()

Stops the muxer.

Once the muxer stops, it can not be restarted.

Throws
IllegalStateException if muxer is in the wrong state.

writeSampleData

Added in API level 18
void writeSampleData (int trackIndex, 
                ByteBuffer byteBuf, 
                MediaCodec.BufferInfo bufferInfo)

Writes an encoded sample into the muxer.

The application needs to make sure that the samples are written into the right tracks. Also, it needs to make sure the samples for each track are written in chronological order (e.g. in the order they are provided by the encoder.)

Parameters
trackIndex int: The track index for this sample.
byteBuf ByteBuffer: The encoded sample.
bufferInfo MediaCodec.BufferInfo: The buffer information related to this sample.
Throws
IllegalArgumentException if trackIndex, byteBuf or bufferInfo is invalid.
IllegalStateException if muxer is in wrong state. MediaMuxer uses the flags provided in MediaCodec.BufferInfo, to signal sync frames.

Protected methods

finalize

Added in API level 18
void finalize ()

Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

The general contract of finalize is that it is invoked if and when the JavaTM virtual machine has determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, except as a result of an action taken by the finalization of some other object or class which is ready to be finalized. The finalize method may take any action, including making this object available again to other threads; the usual purpose of finalize, however, is to perform cleanup actions before the object is irrevocably discarded. For example, the finalize method for an object that represents an input/output connection might perform explicit I/O transactions to break the connection before the object is permanently discarded.

The finalize method of class Object performs no special action; it simply returns normally. Subclasses of Object may override this definition.

The Java programming language does not guarantee which thread will invoke the finalize method for any given object. It is guaranteed, however, that the thread that invokes finalize will not be holding any user-visible synchronization locks when finalize is invoked. If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates.

After the finalize method has been invoked for an object, no further action is taken until the Java virtual machine has again determined that there is no longer any means by which this object can be accessed by any thread that has not yet died, including possible actions by other objects or classes which are ready to be finalized, at which point the object may be discarded.

The finalize method is never invoked more than once by a Java virtual machine for any given object.

Any exception thrown by the finalize method causes the finalization of this object to be halted, but is otherwise ignored.

Throws
Throwable

Hooray!