Android APIs
public final class

MediaSync

extends Object
java.lang.Object
   ↳ android.media.MediaSync

Class Overview

MediaSync class can be used to synchronously playback audio and video streams. It can be used to play audio-only or video-only stream, too.

MediaSync is generally used like this:

 MediaSync sync = new MediaSync();
 sync.setSurface(surface);
 Surface inputSurface = sync.createInputSurface();
 ...
 // MediaCodec videoDecoder = ...;
 videoDecoder.configure(format, inputSurface, ...);
 ...
 sync.setAudioTrack(audioTrack);
 sync.setCallback(new MediaSync.Callback() {
     @Override
     public void onAudioBufferConsumed(MediaSync sync, ByteBuffer audioBuffer, int bufferId) {
         ...
     }
 }, null);
 // This needs to be done since sync is paused on creation.
 sync.setPlaybackParams(new PlaybackParams().setSpeed(1.f));

 for (;;) {
   ...
   // send video frames to surface for rendering, e.g., call
   // videoDecoder.releaseOutputBuffer(videoOutputBufferIx, videoPresentationTimeNs);
   // More details are available as below.
   ...
   sync.queueAudio(audioByteBuffer, bufferId, audioPresentationTimeUs); // non-blocking.
   // The audioByteBuffer and bufferId will be returned via callback.
   // More details are available as below.
   ...
     ...
 }
 sync.setPlaybackParams(new PlaybackParams().setSpeed(0.f));
 sync.release();
 sync = null;

 // The following code snippet illustrates how video/audio raw frames are created by
 // MediaCodec's, how they are fed to MediaSync and how they are returned by MediaSync.
 // This is the callback from MediaCodec.
 onOutputBufferAvailable(MediaCodec codec, int bufferId, BufferInfo info) {
     // ...
     if (codec == videoDecoder) {
         // surface timestamp must contain media presentation time in nanoseconds.
         codec.releaseOutputBuffer(bufferId, 1000 * info.presentationTime);
     } else {
         ByteBuffer audioByteBuffer = codec.getOutputBuffer(bufferId);
         sync.queueAudio(audioByteBuffer, bufferId, info.presentationTime);
     }
     // ...
 }

 // This is the callback from MediaSync.
 onAudioBufferConsumed(MediaSync sync, ByteBuffer buffer, int bufferId) {
     // ...
     audioDecoder.releaseBuffer(bufferId, false);
     // ...
 }

 
The client needs to configure corresponding sink by setting the Surface and/or AudioTrack based on the stream type it will play.

For video, the client needs to call createInputSurface() to obtain a surface on which it will render video frames.

For audio, the client needs to set up audio track correctly, e.g., using MODE_STREAM. The audio buffers are sent to MediaSync directly via queueAudio(ByteBuffer, int, long), and are returned to the client via onAudioBufferConsumed(MediaSync, ByteBuffer, int) asynchronously. The client should not modify an audio buffer till it's returned.

The client can optionally pre-fill audio/video buffers by setting playback rate to 0.0, and then feed audio/video buffers to corresponding components. This can reduce possible initial underrun.

Summary

Nested Classes
class MediaSync.Callback MediaSync callback interface. 
interface MediaSync.OnErrorListener Interface definition of a callback to be invoked when there has been an error during an asynchronous operation (other errors will throw exceptions at method call time). 
Constants
int MEDIASYNC_ERROR_AUDIOTRACK_FAIL Audio track failed.
int MEDIASYNC_ERROR_SURFACE_FAIL The surface failed to handle video buffers.
Public Constructors
MediaSync()
Class constructor.
Public Methods
final Surface createInputSurface()
Requests a Surface to use as the input.
void flush()
Flushes all buffers from the sync object.
PlaybackParams getPlaybackParams()
Gets the playback rate using PlaybackParams.
SyncParams getSyncParams()
Gets the A/V sync mode.
MediaTimestamp getTimestamp()
Get current playback position.
void queueAudio(ByteBuffer audioData, int bufferId, long presentationTimeUs)
Queues the audio data asynchronously for playback (AudioTrack must be in streaming mode).
final void release()
Make sure you call this when you're done to free up any opened component instance instead of relying on the garbage collector to do this for you at some point in the future.
void setAudioTrack(AudioTrack audioTrack)
Sets the audio track for MediaSync.
void setCallback(MediaSync.Callback cb, Handler handler)
Sets an asynchronous callback for actionable MediaSync events.
void setOnErrorListener(MediaSync.OnErrorListener listener, Handler handler)
Sets an asynchronous callback for error events.
void setPlaybackParams(PlaybackParams params)
Sets playback rate using PlaybackParams.
void setSurface(Surface surface)
Sets the output surface for MediaSync.
void setSyncParams(SyncParams params)
Sets A/V sync mode.
Protected Methods
void finalize()
Invoked when the garbage collector has detected that this instance is no longer reachable.
[Expand]
Inherited Methods
From class java.lang.Object

Constants

public static final int MEDIASYNC_ERROR_AUDIOTRACK_FAIL

Added in API level 23

Audio track failed.

Constant Value: 1 (0x00000001)

public static final int MEDIASYNC_ERROR_SURFACE_FAIL

Added in API level 23

The surface failed to handle video buffers.

Constant Value: 2 (0x00000002)

Public Constructors

public MediaSync ()

Added in API level 23

Class constructor. On creation, MediaSync is paused, i.e., playback rate is 0.0f.

Public Methods

public final Surface createInputSurface ()

Added in API level 23

Requests a Surface to use as the input. This may only be called after setSurface(Surface).

The application is responsible for calling release() on the Surface when done.

Throws
IllegalStateException if not set, or another input surface has already been created.

public void flush ()

Added in API level 23

Flushes all buffers from the sync object.

All pending unprocessed audio and video buffers are discarded. If an audio track was configured, it is flushed and stopped. If a video output surface was configured, the last frame queued to it is left on the frame. Queue a blank video frame to clear the surface,

No callbacks are received for the flushed buffers.

Throws
IllegalStateException if the internal player engine has not been initialized.

public PlaybackParams getPlaybackParams ()

Added in API level 23

Gets the playback rate using PlaybackParams.

Returns
  • the playback rate being used.
Throws
IllegalStateException if the internal sync engine or the audio track has not been initialized.

public SyncParams getSyncParams ()

Added in API level 23

Gets the A/V sync mode.

Returns
  • the A/V sync params
Throws
IllegalStateException if the internal player engine has not been initialized.

public MediaTimestamp getTimestamp ()

Added in API level 23

Get current playback position.

The MediaTimestamp represents how the media time correlates to the system time in a linear fashion using an anchor and a clock rate. During regular playback, the media time moves fairly constantly (though the anchor frame may be rebased to a current system time, the linear correlation stays steady). Therefore, this method does not need to be called often.

To help users get current playback position, this method always anchors the timestamp to the current system time, so getAnchorMediaTimeUs() can be used as current playback position.

Returns
  • a MediaTimestamp object if a timestamp is available, or null if no timestamp is available, e.g. because the media player has not been initialized.
See Also

public void queueAudio (ByteBuffer audioData, int bufferId, long presentationTimeUs)

Added in API level 23

Queues the audio data asynchronously for playback (AudioTrack must be in streaming mode). If the audio track was flushed as a result of flush(), it will be restarted.

Parameters
audioData the buffer that holds the data to play. This buffer will be returned to the client via registered callback.
bufferId an integer used to identify audioData. It will be returned to the client along with audioData. This helps applications to keep track of audioData, e.g., it can be used to store the output buffer index used by the audio codec.
presentationTimeUs the presentation timestamp in microseconds for the first frame in the buffer.
Throws
IllegalStateException if audio track is not set or internal configureation has not been done correctly.

public final void release ()

Added in API level 23

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

public void setAudioTrack (AudioTrack audioTrack)

Added in API level 23

Sets the audio track for MediaSync.

Currently, this is only supported in the Initialized state.

Parameters
audioTrack Specify an AudioTrack through which to render the audio data.
Throws
IllegalArgumentException if the audioTrack has been released, or is invalid.
IllegalStateException if setting the audio track is not supported, e.g. not in the Initialized state, or another audio track has already been set.

public void setCallback (MediaSync.Callback cb, Handler handler)

Added in API level 23

Sets an asynchronous callback for actionable MediaSync events.

This method can be called multiple times to update a previously set callback. If the handler is changed, undelivered notifications scheduled for the old handler may be dropped.

Do not call this inside callback.

Parameters
cb The callback that will run. Use null to stop receiving callbacks.
handler The Handler that will run the callback. Use null to use MediaSync's internal handler if it exists.

public void setOnErrorListener (MediaSync.OnErrorListener listener, Handler handler)

Added in API level 23

Sets an asynchronous callback for error events.

This method can be called multiple times to update a previously set listener. If the handler is changed, undelivered notifications scheduled for the old handler may be dropped.

Do not call this inside callback.

Parameters
listener The callback that will run. Use null to stop receiving callbacks.
handler The Handler that will run the callback. Use null to use MediaSync's internal handler if it exists.

public void setPlaybackParams (PlaybackParams params)

Added in API level 23

Sets playback rate using PlaybackParams.

When using MediaSync with AudioTrack, set playback params using this call instead of calling it directly on the track, so that the sync is aware of the params change.

This call also works if there is no audio track.

Parameters
params the playback params to use. Speed is the ratio between desired playback rate and normal one. 1.0 means normal playback speed. 0.0 means pause. Value larger than 1.0 means faster playback, while value between 0.0 and 1.0 for slower playback. Note: the normal rate does not change as a result of this call. To restore the original rate at any time, use speed of 1.0.
Throws
IllegalStateException if the internal sync engine or the audio track has not been initialized.
IllegalArgumentException if the params are not supported.

public void setSurface (Surface surface)

Added in API level 23

Sets the output surface for MediaSync.

Currently, this is only supported in the Initialized state.

Parameters
surface Specify a surface on which to render the video data.
Throws
IllegalArgumentException if the surface has been released, is invalid, or can not be connected.
IllegalStateException if setting the surface is not supported, e.g. not in the Initialized state, or another surface has already been set.

public void setSyncParams (SyncParams params)

Added in API level 23

Sets A/V sync mode.

Parameters
params the A/V sync params to apply
Throws
IllegalStateException if the internal player engine has not been initialized.
IllegalArgumentException if params are not supported.

Protected Methods

protected void finalize ()

Added in API level 23

Invoked when the garbage collector has detected that this instance is no longer reachable. The default implementation does nothing, but this method can be overridden to free resources.

Note that objects that override finalize are significantly more expensive than objects that don't. Finalizers may be run a long time after the object is no longer reachable, depending on memory pressure, so it's a bad idea to rely on them for cleanup. Note also that finalizers are run on a single VM-wide finalizer thread, so doing blocking work in a finalizer is a bad idea. A finalizer is usually only necessary for a class that has a native peer and needs to call a native method to destroy that peer. Even then, it's better to provide an explicit close method (and implement Closeable), and insist that callers manually dispose of instances. This works well for something like files, but less well for something like a BigInteger where typical calling code would have to deal with lots of temporaries. Unfortunately, code that creates lots of temporaries is the worst kind of code from the point of view of the single finalizer thread.

If you must use finalizers, consider at least providing your own ReferenceQueue and having your own thread process that queue.

Unlike constructors, finalizers are not automatically chained. You are responsible for calling super.finalize() yourself.

Uncaught exceptions thrown by finalizers are ignored and do not terminate the finalizer thread. See Effective Java Item 7, "Avoid finalizers" for more.