MediaPlayer.java revision cf4550c3198d6b3d92cdc52707fe70d7cc0caa9f
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.media;
18
19import android.content.ContentResolver;
20import android.content.Context;
21import android.content.res.AssetFileDescriptor;
22import android.net.Uri;
23import android.os.Handler;
24import android.os.Looper;
25import android.os.Message;
26import android.os.ParcelFileDescriptor;
27import android.os.PowerManager;
28import android.util.Log;
29import android.view.Surface;
30import android.view.SurfaceHolder;
31import android.graphics.Bitmap;
32import android.media.AudioManager;
33
34import java.io.FileDescriptor;
35import java.io.IOException;
36
37import java.lang.ref.WeakReference;
38
39/**
40 * MediaPlayer class can be used to control playback
41 * of audio/video files and streams. An example on how to use the methods in
42 * this class can be found in {@link android.widget.VideoView}.
43 * Please see <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a>
44 * for additional help using MediaPlayer.
45 *
46 * <p>Topics covered here are:
47 * <ol>
48 * <li><a href="#StateDiagram">State Diagram</a>
49 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
50 * <li><a href="#Permissions">Permissions</a>
51 * </ol>
52 *
53 * <a name="StateDiagram"></a>
54 * <h3>State Diagram</h3>
55 *
56 * <p>Playback control of audio/video files and streams is managed as a state
57 * machine. The following diagram shows the life cycle and the states of a
58 * MediaPlayer object driven by the supported playback control operations.
59 * The ovals represent the states a MediaPlayer object may reside
60 * in. The arcs represent the playback control operations that drive the object
61 * state transition. There are two types of arcs. The arcs with a single arrow
62 * head represent synchronous method calls, while those with
63 * a double arrow head represent asynchronous method calls.</p>
64 *
65 * <p><img src="../../../images/mediaplayer_state_diagram.gif"
66 *         alt="MediaPlayer State diagram"
67 *         border="0" /></p>
68 *
69 * <p>From this state diagram, one can see that a MediaPlayer object has the
70 *    following states:</p>
71 * <ul>
72 *     <li>When a MediaPlayer object is just created using <code>new</code> or
73 *         after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
74 *         {@link #release()} is called, it is in the <em>End</em> state. Between these
75 *         two states is the life cycle of the MediaPlayer object.
76 *         <ul>
77 *         <li>There is a subtle but important difference between a newly constructed
78 *         MediaPlayer object and the MediaPlayer object after {@link #reset()}
79 *         is called. It is a programming error to invoke methods such
80 *         as {@link #getCurrentPosition()},
81 *         {@link #getDuration()}, {@link #getVideoHeight()},
82 *         {@link #getVideoWidth()}, {@link #setAudioStreamType(int)},
83 *         {@link #setLooping(boolean)},
84 *         {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
85 *         {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or
86 *         {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
87 *         methods is called right after a MediaPlayer object is constructed,
88 *         the user supplied callback method OnErrorListener.onError() won't be
89 *         called by the internal player engine and the object state remains
90 *         unchanged; but if these methods are called right after {@link #reset()},
91 *         the user supplied callback method OnErrorListener.onError() will be
92 *         invoked by the internal player engine and the object will be
93 *         transfered to the <em>Error</em> state. </li>
94 *         <li>It is also recommended that once
95 *         a MediaPlayer object is no longer being used, call {@link #release()} immediately
96 *         so that resources used by the internal player engine associated with the
97 *         MediaPlayer object can be released immediately. Resource may include
98 *         singleton resources such as hardware acceleration components and
99 *         failure to call {@link #release()} may cause subsequent instances of
100 *         MediaPlayer objects to fallback to software implementations or fail
101 *         altogether. Once the MediaPlayer
102 *         object is in the <em>End</em> state, it can no longer be used and
103 *         there is no way to bring it back to any other state. </li>
104 *         <li>Furthermore,
105 *         the MediaPlayer objects created using <code>new</code> is in the
106 *         <em>Idle</em> state, while those created with one
107 *         of the overloaded convenient <code>create</code> methods are <em>NOT</em>
108 *         in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
109 *         state if the creation using <code>create</code> method is successful.
110 *         </li>
111 *         </ul>
112 *         </li>
113 *     <li>In general, some playback control operation may fail due to various
114 *         reasons, such as unsupported audio/video format, poorly interleaved
115 *         audio/video, resolution too high, streaming timeout, and the like.
116 *         Thus, error reporting and recovery is an important concern under
117 *         these circumstances. Sometimes, due to programming errors, invoking a playback
118 *         control operation in an invalid state may also occur. Under all these
119 *         error conditions, the internal player engine invokes a user supplied
120 *         OnErrorListener.onError() method if an OnErrorListener has been
121 *         registered beforehand via
122 *         {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
123 *         <ul>
124 *         <li>It is important to note that once an error occurs, the
125 *         MediaPlayer object enters the <em>Error</em> state (except as noted
126 *         above), even if an error listener has not been registered by the application.</li>
127 *         <li>In order to reuse a MediaPlayer object that is in the <em>
128 *         Error</em> state and recover from the error,
129 *         {@link #reset()} can be called to restore the object to its <em>Idle</em>
130 *         state.</li>
131 *         <li>It is good programming practice to have your application
132 *         register a OnErrorListener to look out for error notifications from
133 *         the internal player engine.</li>
134 *         <li>IlleglStateException is
135 *         thrown to prevent programming errors such as calling {@link #prepare()},
136 *         {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
137 *         </code> methods in an invalid state. </li>
138 *         </ul>
139 *         </li>
140 *     <li>Calling
141 *         {@link #setDataSource(FileDescriptor)}, or
142 *         {@link #setDataSource(String)}, or
143 *         {@link #setDataSource(Context, Uri)}, or
144 *         {@link #setDataSource(FileDescriptor, long, long)} transfers a
145 *         MediaPlayer object in the <em>Idle</em> state to the
146 *         <em>Initialized</em> state.
147 *         <ul>
148 *         <li>An IllegalStateException is thrown if
149 *         setDataSource() is called in any other state.</li>
150 *         <li>It is good programming
151 *         practice to always look out for <code>IllegalArgumentException</code>
152 *         and <code>IOException</code> that may be thrown from the overloaded
153 *         <code>setDataSource</code> methods.</li>
154 *         </ul>
155 *         </li>
156 *     <li>A MediaPlayer object must first enter the <em>Prepared</em> state
157 *         before playback can be started.
158 *         <ul>
159 *         <li>There are two ways (synchronous vs.
160 *         asynchronous) that the <em>Prepared</em> state can be reached:
161 *         either a call to {@link #prepare()} (synchronous) which
162 *         transfers the object to the <em>Prepared</em> state once the method call
163 *         returns, or a call to {@link #prepareAsync()} (asynchronous) which
164 *         first transfers the object to the <em>Preparing</em> state after the
165 *         call returns (which occurs almost right way) while the internal
166 *         player engine continues working on the rest of preparation work
167 *         until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
168 *         the internal player engine then calls a user supplied callback method,
169 *         onPrepared() of the OnPreparedListener interface, if an
170 *         OnPreparedListener is registered beforehand via {@link
171 *         #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
172 *         <li>It is important to note that
173 *         the <em>Preparing</em> state is a transient state, and the behavior
174 *         of calling any method with side effect while a MediaPlayer object is
175 *         in the <em>Preparing</em> state is undefined.</li>
176 *         <li>An IllegalStateException is
177 *         thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
178 *         any other state.</li>
179 *         <li>While in the <em>Prepared</em> state, properties
180 *         such as audio/sound volume, screenOnWhilePlaying, looping can be
181 *         adjusted by invoking the corresponding set methods.</li>
182 *         </ul>
183 *         </li>
184 *     <li>To start the playback, {@link #start()} must be called. After
185 *         {@link #start()} returns successfully, the MediaPlayer object is in the
186 *         <em>Started</em> state. {@link #isPlaying()} can be called to test
187 *         whether the MediaPlayer object is in the <em>Started</em> state.
188 *         <ul>
189 *         <li>While in the <em>Started</em> state, the internal player engine calls
190 *         a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
191 *         method if a OnBufferingUpdateListener has been registered beforehand
192 *         via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
193 *         This callback allows applications to keep track of the buffering status
194 *         while streaming audio/video.</li>
195 *         <li>Calling {@link #start()} has not effect
196 *         on a MediaPlayer object that is already in the <em>Started</em> state.</li>
197 *         </ul>
198 *         </li>
199 *     <li>Playback can be paused and stopped, and the current playback position
200 *         can be adjusted. Playback can be paused via {@link #pause()}. When the call to
201 *         {@link #pause()} returns, the MediaPlayer object enters the
202 *         <em>Paused</em> state. Note that the transition from the <em>Started</em>
203 *         state to the <em>Paused</em> state and vice versa happens
204 *         asynchronously in the player engine. It may take some time before
205 *         the state is updated in calls to {@link #isPlaying()}, and it can be
206 *         a number of seconds in the case of streamed content.
207 *         <ul>
208 *         <li>Calling {@link #start()} to resume playback for a paused
209 *         MediaPlayer object, and the resumed playback
210 *         position is the same as where it was paused. When the call to
211 *         {@link #start()} returns, the paused MediaPlayer object goes back to
212 *         the <em>Started</em> state.</li>
213 *         <li>Calling {@link #pause()} has no effect on
214 *         a MediaPlayer object that is already in the <em>Paused</em> state.</li>
215 *         </ul>
216 *         </li>
217 *     <li>Calling  {@link #stop()} stops playback and causes a
218 *         MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
219 *         </em> or <em>PlaybackCompleted</em> state to enter the
220 *         <em>Stopped</em> state.
221 *         <ul>
222 *         <li>Once in the <em>Stopped</em> state, playback cannot be started
223 *         until {@link #prepare()} or {@link #prepareAsync()} are called to set
224 *         the MediaPlayer object to the <em>Prepared</em> state again.</li>
225 *         <li>Calling {@link #stop()} has no effect on a MediaPlayer
226 *         object that is already in the <em>Stopped</em> state.</li>
227 *         </ul>
228 *         </li>
229 *     <li>The playback position can be adjusted with a call to
230 *         {@link #seekTo(int)}.
231 *         <ul>
232 *         <li>Although the asynchronuous {@link #seekTo(int)}
233 *         call returns right way, the actual seek operation may take a while to
234 *         finish, especially for audio/video being streamed. When the actual
235 *         seek operation completes, the internal player engine calls a user
236 *         supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
237 *         has been registered beforehand via
238 *         {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
239 *         <li>Please
240 *         note that {@link #seekTo(int)} can also be called in the other states,
241 *         such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
242 *         </em> state.</li>
243 *         <li>Furthermore, the actual current playback position
244 *         can be retrieved with a call to {@link #getCurrentPosition()}, which
245 *         is helpful for applications such as a Music player that need to keep
246 *         track of the playback progress.</li>
247 *         </ul>
248 *         </li>
249 *     <li>When the playback reaches the end of stream, the playback completes.
250 *         <ul>
251 *         <li>If the looping mode was being set to <var>true</var>with
252 *         {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
253 *         the <em>Started</em> state.</li>
254 *         <li>If the looping mode was set to <var>false
255 *         </var>, the player engine calls a user supplied callback method,
256 *         OnCompletion.onCompletion(), if a OnCompletionListener is registered
257 *         beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
258 *         The invoke of the callback signals that the object is now in the <em>
259 *         PlaybackCompleted</em> state.</li>
260 *         <li>While in the <em>PlaybackCompleted</em>
261 *         state, calling {@link #start()} can restart the playback from the
262 *         beginning of the audio/video source.</li>
263 * </ul>
264 *
265 *
266 * <a name="Valid_and_Invalid_States"></a>
267 * <h3>Valid and invalid states</h3>
268 *
269 * <table border="0" cellspacing="0" cellpadding="0">
270 * <tr><td>Method Name </p></td>
271 *     <td>Valid Sates </p></td>
272 *     <td>Invalid States </p></td>
273 *     <td>Comments </p></td></tr>
274 * <tr><td>getCurrentPosition </p></td>
275 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
276 *         PlaybackCompleted} </p></td>
277 *     <td>{Error}</p></td>
278 *     <td>Successful invoke of this method in a valid state does not change the
279 *         state. Calling this method in an invalid state transfers the object
280 *         to the <em>Error</em> state. </p></td></tr>
281 * <tr><td>getDuration </p></td>
282 *     <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
283 *     <td>{Idle, Initialized, Error} </p></td>
284 *     <td>Successful invoke of this method in a valid state does not change the
285 *         state. Calling this method in an invalid state transfers the object
286 *         to the <em>Error</em> state. </p></td></tr>
287 * <tr><td>getVideoHeight </p></td>
288 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
289 *         PlaybackCompleted}</p></td>
290 *     <td>{Error}</p></td>
291 *     <td>Successful invoke of this method in a valid state does not change the
292 *         state. Calling this method in an invalid state transfers the object
293 *         to the <em>Error</em> state.  </p></td></tr>
294 * <tr><td>getVideoWidth </p></td>
295 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
296 *         PlaybackCompleted}</p></td>
297 *     <td>{Error}</p></td>
298 *     <td>Successful invoke of this method in a valid state does not change
299 *         the state. Calling this method in an invalid state transfers the
300 *         object to the <em>Error</em> state. </p></td></tr>
301 * <tr><td>isPlaying </p></td>
302 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
303 *          PlaybackCompleted}</p></td>
304 *     <td>{Error}</p></td>
305 *     <td>Successful invoke of this method in a valid state does not change
306 *         the state. Calling this method in an invalid state transfers the
307 *         object to the <em>Error</em> state. </p></td></tr>
308 * <tr><td>pause </p></td>
309 *     <td>{Started, Paused}</p></td>
310 *     <td>{Idle, Initialized, Prepared, Stopped, PlaybackCompleted, Error}</p></td>
311 *     <td>Successful invoke of this method in a valid state transfers the
312 *         object to the <em>Paused</em> state. Calling this method in an
313 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
314 * <tr><td>prepare </p></td>
315 *     <td>{Initialized, Stopped} </p></td>
316 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
317 *     <td>Successful invoke of this method in a valid state transfers the
318 *         object to the <em>Prepared</em> state. Calling this method in an
319 *         invalid state throws an IllegalStateException.</p></td></tr>
320 * <tr><td>prepareAsync </p></td>
321 *     <td>{Initialized, Stopped} </p></td>
322 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
323 *     <td>Successful invoke of this method in a valid state transfers the
324 *         object to the <em>Preparing</em> state. Calling this method in an
325 *         invalid state throws an IllegalStateException.</p></td></tr>
326 * <tr><td>release </p></td>
327 *     <td>any </p></td>
328 *     <td>{} </p></td>
329 *     <td>After {@link #release()}, the object is no longer available. </p></td></tr>
330 * <tr><td>reset </p></td>
331 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
332 *         PlaybackCompleted, Error}</p></td>
333 *     <td>{}</p></td>
334 *     <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
335 * <tr><td>seekTo </p></td>
336 *     <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
337 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
338 *     <td>Successful invoke of this method in a valid state does not change
339 *         the state. Calling this method in an invalid state transfers the
340 *         object to the <em>Error</em> state. </p></td></tr>
341 * <tr><td>setAudioStreamType </p></td>
342 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
343 *          PlaybackCompleted}</p></td>
344 *     <td>{Error}</p></td>
345 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
346 * <tr><td>setDataSource </p></td>
347 *     <td>{Idle} </p></td>
348 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
349 *          Error} </p></td>
350 *     <td>Successful invoke of this method in a valid state transfers the
351 *         object to the <em>Initialized</em> state. Calling this method in an
352 *         invalid state throws an IllegalStateException.</p></td></tr>
353 * <tr><td>setDisplay </p></td>
354 *     <td>any </p></td>
355 *     <td>{} </p></td>
356 *     <td>This method can be called in any state and calling it does not change
357 *         the object state. </p></td></tr>
358 * <tr><td>setLooping </p></td>
359 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
360 *         PlaybackCompleted}</p></td>
361 *     <td>{Error}</p></td>
362 *     <td>Successful invoke of this method in a valid state does not change
363 *         the state. Calling this method in an
364 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
365 * <tr><td>isLooping </p></td>
366 *     <td>any </p></td>
367 *     <td>{} </p></td>
368 *     <td>This method can be called in any state and calling it does not change
369 *         the object state. </p></td></tr>
370 * <tr><td>setOnBufferingUpdateListener </p></td>
371 *     <td>any </p></td>
372 *     <td>{} </p></td>
373 *     <td>This method can be called in any state and calling it does not change
374 *         the object state. </p></td></tr>
375 * <tr><td>setOnCompletionListener </p></td>
376 *     <td>any </p></td>
377 *     <td>{} </p></td>
378 *     <td>This method can be called in any state and calling it does not change
379 *         the object state. </p></td></tr>
380 * <tr><td>setOnErrorListener </p></td>
381 *     <td>any </p></td>
382 *     <td>{} </p></td>
383 *     <td>This method can be called in any state and calling it does not change
384 *         the object state. </p></td></tr>
385 * <tr><td>setOnPreparedListener </p></td>
386 *     <td>any </p></td>
387 *     <td>{} </p></td>
388 *     <td>This method can be called in any state and calling it does not change
389 *         the object state. </p></td></tr>
390 * <tr><td>setOnSeekCompleteListener </p></td>
391 *     <td>any </p></td>
392 *     <td>{} </p></td>
393 *     <td>This method can be called in any state and calling it does not change
394 *         the object state. </p></td></tr>
395 * <tr><td>setScreenOnWhilePlaying</></td>
396 *     <td>any </p></td>
397 *     <td>{} </p></td>
398 *     <td>This method can be called in any state and calling it does not change
399 *         the object state.  </p></td></tr>
400 * <tr><td>setVolume </p></td>
401 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
402 *          PlaybackCompleted}</p></td>
403 *     <td>{Error}</p></td>
404 *     <td>Successful invoke of this method does not change the state.
405 * <tr><td>setWakeMode </p></td>
406 *     <td>any </p></td>
407 *     <td>{} </p></td>
408 *     <td>This method can be called in any state and calling it does not change
409 *         the object state.</p></td></tr>
410 * <tr><td>start </p></td>
411 *     <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
412 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
413 *     <td>Successful invoke of this method in a valid state transfers the
414 *         object to the <em>Started</em> state. Calling this method in an
415 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
416 * <tr><td>stop </p></td>
417 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
418 *     <td>{Idle, Initialized, Error}</p></td>
419 *     <td>Successful invoke of this method in a valid state transfers the
420 *         object to the <em>Stopped</em> state. Calling this method in an
421 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
422 * </table>
423 *
424 * <a name="Permissions"></a>
425 * <h3>Permissions</h3>
426 * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
427 * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
428 * element.
429 *
430 */
431public class MediaPlayer
432{
433    static {
434        System.loadLibrary("media_jni");
435    }
436
437    private final static String TAG = "MediaPlayer";
438
439    private int mNativeContext; // accessed by native methods
440    private int mListenerContext; // accessed by native methods
441    private Surface mSurface; // accessed by native methods
442    private SurfaceHolder  mSurfaceHolder;
443    private EventHandler mEventHandler;
444    private PowerManager.WakeLock mWakeLock = null;
445    private boolean mScreenOnWhilePlaying;
446    private boolean mStayAwake;
447
448    /**
449     * Default constructor. Consider using one of the create() methods for
450     * synchronously instantiating a MediaPlayer from a Uri or resource.
451     * <p>When done with the MediaPlayer, you should call  {@link #release()},
452     * to free the resources. If not released, too many MediaPlayer instances may
453     * result in an exception.</p>
454     */
455    public MediaPlayer() {
456
457        Looper looper;
458        if ((looper = Looper.myLooper()) != null) {
459            mEventHandler = new EventHandler(this, looper);
460        } else if ((looper = Looper.getMainLooper()) != null) {
461            mEventHandler = new EventHandler(this, looper);
462        } else {
463            mEventHandler = null;
464        }
465
466        /* Native setup requires a weak reference to our object.
467         * It's easier to create it here than in C++.
468         */
469        native_setup(new WeakReference<MediaPlayer>(this));
470    }
471
472    /*
473     * Update the MediaPlayer ISurface. Call after updating mSurface.
474     */
475    private native void _setVideoSurface();
476
477    /**
478     * Sets the SurfaceHolder to use for displaying the video portion of the media.
479     * This call is optional. Not calling it when playing back a video will
480     * result in only the audio track being played.
481     *
482     * @param sh the SurfaceHolder to use for video display
483     */
484    public void setDisplay(SurfaceHolder sh) {
485        mSurfaceHolder = sh;
486        if (sh != null) {
487            mSurface = sh.getSurface();
488        } else {
489            mSurface = null;
490        }
491        _setVideoSurface();
492        updateSurfaceScreenOn();
493    }
494
495    /**
496     * Convenience method to create a MediaPlayer for a given Uri.
497     * On success, {@link #prepare()} will already have been called and must not be called again.
498     * <p>When done with the MediaPlayer, you should call  {@link #release()},
499     * to free the resources. If not released, too many MediaPlayer instances will
500     * result in an exception.</p>
501     *
502     * @param context the Context to use
503     * @param uri the Uri from which to get the datasource
504     * @return a MediaPlayer object, or null if creation failed
505     */
506    public static MediaPlayer create(Context context, Uri uri) {
507        return create (context, uri, null);
508    }
509
510    /**
511     * Convenience method to create a MediaPlayer for a given Uri.
512     * On success, {@link #prepare()} will already have been called and must not be called again.
513     * <p>When done with the MediaPlayer, you should call  {@link #release()},
514     * to free the resources. If not released, too many MediaPlayer instances will
515     * result in an exception.</p>
516     *
517     * @param context the Context to use
518     * @param uri the Uri from which to get the datasource
519     * @param holder the SurfaceHolder to use for displaying the video
520     * @return a MediaPlayer object, or null if creation failed
521     */
522    public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
523
524        try {
525            MediaPlayer mp = new MediaPlayer();
526            mp.setDataSource(context, uri);
527            if (holder != null) {
528                mp.setDisplay(holder);
529            }
530            mp.prepare();
531            return mp;
532        } catch (IOException ex) {
533            Log.d(TAG, "create failed:", ex);
534            // fall through
535        } catch (IllegalArgumentException ex) {
536            Log.d(TAG, "create failed:", ex);
537            // fall through
538        } catch (SecurityException ex) {
539            Log.d(TAG, "create failed:", ex);
540            // fall through
541        }
542
543        return null;
544    }
545
546    /**
547     * Convenience method to create a MediaPlayer for a given resource id.
548     * On success, {@link #prepare()} will already have been called and must not be called again.
549     * <p>When done with the MediaPlayer, you should call  {@link #release()},
550     * to free the resources. If not released, too many MediaPlayer instances will
551     * result in an exception.</p>
552     *
553     * @param context the Context to use
554     * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
555     *              the resource to use as the datasource
556     * @return a MediaPlayer object, or null if creation failed
557     */
558    public static MediaPlayer create(Context context, int resid) {
559        try {
560            AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
561            if (afd == null) return null;
562
563            MediaPlayer mp = new MediaPlayer();
564            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
565            afd.close();
566            mp.prepare();
567            return mp;
568        } catch (IOException ex) {
569            Log.d(TAG, "create failed:", ex);
570            // fall through
571        } catch (IllegalArgumentException ex) {
572            Log.d(TAG, "create failed:", ex);
573           // fall through
574        } catch (SecurityException ex) {
575            Log.d(TAG, "create failed:", ex);
576            // fall through
577        }
578        return null;
579    }
580
581    /**
582     * Sets the data source as a content Uri.
583     *
584     * @param context the Context to use when resolving the Uri
585     * @param uri the Content URI of the data you want to play
586     * @throws IllegalStateException if it is called in an invalid state
587     */
588    public void setDataSource(Context context, Uri uri)
589        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
590
591        String scheme = uri.getScheme();
592        if(scheme == null || scheme.equals("file")) {
593            setDataSource(uri.getPath());
594            return;
595        }
596
597        AssetFileDescriptor fd = null;
598        try {
599            ContentResolver resolver = context.getContentResolver();
600            fd = resolver.openAssetFileDescriptor(uri, "r");
601            if (fd == null) {
602                return;
603            }
604            // Note: using getDeclaredLength so that our behavior is the same
605            // as previous versions when the content provider is returning
606            // a full file.
607            if (fd.getDeclaredLength() < 0) {
608                setDataSource(fd.getFileDescriptor());
609            } else {
610                setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength());
611            }
612            return;
613        } catch (SecurityException ex) {
614        } catch (IOException ex) {
615        } finally {
616            if (fd != null) {
617                fd.close();
618            }
619        }
620        Log.d(TAG, "Couldn't open file on client side, trying server side");
621        setDataSource(uri.toString());
622        return;
623    }
624
625    /**
626     * Sets the data source (file-path or http/rtsp URL) to use.
627     *
628     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
629     * @throws IllegalStateException if it is called in an invalid state
630     */
631    public native void setDataSource(String path) throws IOException, IllegalArgumentException, IllegalStateException;
632
633    /**
634     * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
635     * to close the file descriptor. It is safe to do so as soon as this call returns.
636     *
637     * @param fd the FileDescriptor for the file you want to play
638     * @throws IllegalStateException if it is called in an invalid state
639     */
640    public void setDataSource(FileDescriptor fd)
641            throws IOException, IllegalArgumentException, IllegalStateException {
642        // intentionally less than LONG_MAX
643        setDataSource(fd, 0, 0x7ffffffffffffffL);
644    }
645
646    /**
647     * Sets the data source (FileDescriptor) to use.  It is the caller's responsibility
648     * to close the file descriptor. It is safe to do so as soon as this call returns.
649     *
650     * @param fd the FileDescriptor for the file you want to play
651     * @param offset the offset into the file where the data to be played starts, in bytes
652     * @param length the length in bytes of the data to be played
653     * @throws IllegalStateException if it is called in an invalid state
654     */
655    public native void setDataSource(FileDescriptor fd, long offset, long length)
656            throws IOException, IllegalArgumentException, IllegalStateException;
657
658    /**
659     * Prepares the player for playback, synchronously.
660     *
661     * After setting the datasource and the display surface, you need to either
662     * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
663     * which blocks until MediaPlayer is ready for playback.
664     *
665     * @throws IllegalStateException if it is called in an invalid state
666     */
667    public native void prepare() throws IOException, IllegalStateException;
668
669    /**
670     * Prepares the player for playback, asynchronously.
671     *
672     * After setting the datasource and the display surface, you need to either
673     * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
674     * which returns immediately, rather than blocking until enough data has been
675     * buffered.
676     *
677     * @throws IllegalStateException if it is called in an invalid state
678     */
679    public native void prepareAsync() throws IllegalStateException;
680
681    /**
682     * Starts or resumes playback. If playback had previously been paused,
683     * playback will continue from where it was paused. If playback had
684     * been stopped, or never started before, playback will start at the
685     * beginning.
686     *
687     * @throws IllegalStateException if it is called in an invalid state
688     */
689    public  void start() throws IllegalStateException {
690        stayAwake(true);
691        _start();
692    }
693
694    private native void _start() throws IllegalStateException;
695
696    /**
697     * Stops playback after playback has been stopped or paused.
698     *
699     * @throws IllegalStateException if the internal player engine has not been
700     * initialized.
701     */
702    public void stop() throws IllegalStateException {
703        stayAwake(false);
704        _stop();
705    }
706
707    private native void _stop() throws IllegalStateException;
708
709    /**
710     * Pauses playback. Call start() to resume.
711     *
712     * @throws IllegalStateException if the internal player engine has not been
713     * initialized.
714     */
715    public void pause() throws IllegalStateException {
716        stayAwake(false);
717        _pause();
718    }
719
720    private native void _pause() throws IllegalStateException;
721
722    /**
723     * Set the low-level power management behavior for this MediaPlayer.  This
724     * can be used when the MediaPlayer is not playing through a SurfaceHolder
725     * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
726     * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
727     *
728     * <p>This function has the MediaPlayer access the low-level power manager
729     * service to control the device's power usage while playing is occurring.
730     * The parameter is a combination of {@link android.os.PowerManager} wake flags.
731     * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
732     * permission.
733     * By default, no attempt is made to keep the device awake during playback.
734     *
735     * @param context the Context to use
736     * @param mode    the power/wake mode to set
737     * @see android.os.PowerManager
738     */
739    public void setWakeMode(Context context, int mode) {
740        boolean washeld = false;
741        if (mWakeLock != null) {
742            if (mWakeLock.isHeld()) {
743                washeld = true;
744                mWakeLock.release();
745            }
746            mWakeLock = null;
747        }
748
749        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
750        mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
751        mWakeLock.setReferenceCounted(false);
752        if (washeld) {
753            mWakeLock.acquire();
754        }
755    }
756
757    /**
758     * Control whether we should use the attached SurfaceHolder to keep the
759     * screen on while video playback is occurring.  This is the preferred
760     * method over {@link #setWakeMode} where possible, since it doesn't
761     * require that the application have permission for low-level wake lock
762     * access.
763     *
764     * @param screenOn Supply true to keep the screen on, false to allow it
765     * to turn off.
766     */
767    public void setScreenOnWhilePlaying(boolean screenOn) {
768        if (mScreenOnWhilePlaying != screenOn) {
769            mScreenOnWhilePlaying = screenOn;
770            updateSurfaceScreenOn();
771        }
772    }
773
774    private void stayAwake(boolean awake) {
775        if (mWakeLock != null) {
776            if (awake && !mWakeLock.isHeld()) {
777                mWakeLock.acquire();
778            } else if (!awake && mWakeLock.isHeld()) {
779                mWakeLock.release();
780            }
781        }
782        mStayAwake = awake;
783        updateSurfaceScreenOn();
784    }
785
786    private void updateSurfaceScreenOn() {
787        if (mSurfaceHolder != null) {
788            mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
789        }
790    }
791
792    /**
793     * Returns the width of the video.
794     *
795     * @return the width of the video, or 0 if there is no video,
796     * no display surface was set, or prepare()/prepareAsync()
797     * have not completed yet
798     */
799    public native int getVideoWidth();
800
801    /**
802     * Returns the height of the video.
803     *
804     * @return the height of the video, or 0 if there is no video,
805     * no display surface was set, or prepare()/prepareAsync()
806     * have not completed yet
807     */
808    public native int getVideoHeight();
809
810    /**
811     * Checks whether the MediaPlayer is playing.
812     *
813     * @return true if currently playing, false otherwise
814     */
815    public native boolean isPlaying();
816
817    /**
818     * Seeks to specified time position.
819     *
820     * @param msec the offset in milliseconds from the start to seek to
821     * @throws IllegalStateException if the internal player engine has not been
822     * initialized
823     */
824    public native void seekTo(int msec) throws IllegalStateException;
825
826    /**
827     * Gets the current playback position.
828     *
829     * @return the current position in milliseconds
830     */
831    public native int getCurrentPosition();
832
833    /**
834     * Gets the duration of the file.
835     *
836     * @return the duration in milliseconds
837     */
838    public native int getDuration();
839
840    /**
841     * Releases resources associated with this MediaPlayer object.
842     * It is considered good practice to call this method when you're
843     * done using the MediaPlayer.
844     */
845    public void release() {
846        stayAwake(false);
847        updateSurfaceScreenOn();
848        mOnPreparedListener = null;
849        mOnBufferingUpdateListener = null;
850        mOnCompletionListener = null;
851        mOnSeekCompleteListener = null;
852        mOnErrorListener = null;
853        mOnInfoListener = null;
854        mOnVideoSizeChangedListener = null;
855        _release();
856    }
857
858    private native void _release();
859
860    /**
861     * Resets the MediaPlayer to its uninitialized state. After calling
862     * this method, you will have to initialize it again by setting the
863     * data source and calling prepare().
864     */
865    public void reset() {
866        stayAwake(false);
867        _reset();
868        // make sure none of the listeners get called anymore
869        mEventHandler.removeCallbacksAndMessages(null);
870    }
871
872    private native void _reset();
873
874    /**
875     * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
876     * for a list of stream types.
877     *
878     * @param streamtype the audio stream type
879     * @see android.media.AudioManager
880     */
881    public native void setAudioStreamType(int streamtype);
882
883    /**
884     * Sets the player to be looping or non-looping.
885     *
886     * @param looping whether to loop or not
887     */
888    public native void setLooping(boolean looping);
889
890    /**
891     * Checks whether the MediaPlayer is looping or non-looping.
892     *
893     * @return true if the MediaPlayer is currently looping, false otherwise
894     */
895    public native boolean isLooping();
896
897    /**
898     * Sets the volume on this player.
899     * This API is recommended for balancing the output of audio streams
900     * within an application. Unless you are writing an application to
901     * control user settings, this API should be used in preference to
902     * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
903     * a particular type. Note that the passed volume values are raw scalars.
904     * UI controls should be scaled logarithmically.
905     *
906     * @param leftVolume left volume scalar
907     * @param rightVolume right volume scalar
908     */
909    public native void setVolume(float leftVolume, float rightVolume);
910
911    /**
912     * Currently not implemented, returns null.
913     * @deprecated
914     * @hide
915     */
916    public native Bitmap getFrameAt(int msec) throws IllegalStateException;
917
918    private native final void native_setup(Object mediaplayer_this);
919    private native final void native_finalize();
920    @Override
921    protected void finalize() { native_finalize(); }
922
923    /* Do not change these values without updating their counterparts
924     * in include/media/mediaplayer.h!
925     */
926    private static final int MEDIA_NOP = 0; // interface test message
927    private static final int MEDIA_PREPARED = 1;
928    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
929    private static final int MEDIA_BUFFERING_UPDATE = 3;
930    private static final int MEDIA_SEEK_COMPLETE = 4;
931    private static final int MEDIA_SET_VIDEO_SIZE = 5;
932    private static final int MEDIA_ERROR = 100;
933    private static final int MEDIA_INFO = 200;
934
935    private class EventHandler extends Handler
936    {
937        private MediaPlayer mMediaPlayer;
938
939        public EventHandler(MediaPlayer mp, Looper looper) {
940            super(looper);
941            mMediaPlayer = mp;
942        }
943
944        @Override
945        public void handleMessage(Message msg) {
946            if (mMediaPlayer.mNativeContext == 0) {
947                Log.w(TAG, "mediaplayer went away with unhandled events");
948                return;
949            }
950            switch(msg.what) {
951            case MEDIA_PREPARED:
952                if (mOnPreparedListener != null)
953                    mOnPreparedListener.onPrepared(mMediaPlayer);
954                return;
955
956            case MEDIA_PLAYBACK_COMPLETE:
957                if (mOnCompletionListener != null)
958                    mOnCompletionListener.onCompletion(mMediaPlayer);
959                stayAwake(false);
960                return;
961
962            case MEDIA_BUFFERING_UPDATE:
963                if (mOnBufferingUpdateListener != null)
964                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
965                return;
966
967            case MEDIA_SEEK_COMPLETE:
968              if (mOnSeekCompleteListener != null)
969                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
970              return;
971
972            case MEDIA_SET_VIDEO_SIZE:
973              if (mOnVideoSizeChangedListener != null)
974                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
975              return;
976
977            case MEDIA_ERROR:
978                // For PV specific error values (msg.arg2) look in
979                // opencore/pvmi/pvmf/include/pvmf_return_codes.h
980                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
981                boolean error_was_handled = false;
982                if (mOnErrorListener != null) {
983                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
984                }
985                if (mOnCompletionListener != null && ! error_was_handled) {
986                    mOnCompletionListener.onCompletion(mMediaPlayer);
987                }
988                stayAwake(false);
989                return;
990
991            case MEDIA_INFO:
992                // For PV specific code values (msg.arg2) look in
993                // opencore/pvmi/pvmf/include/pvmf_return_codes.h
994                Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
995                if (mOnInfoListener != null) {
996                    mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
997                }
998                // No real default action so far.
999                return;
1000
1001            case MEDIA_NOP: // interface test message - ignore
1002                break;
1003
1004            default:
1005                Log.e(TAG, "Unknown message type " + msg.what);
1006                return;
1007            }
1008        }
1009    }
1010
1011    /**
1012     * Called from native code when an interesting event happens.  This method
1013     * just uses the EventHandler system to post the event back to the main app thread.
1014     * We use a weak reference to the original MediaPlayer object so that the native
1015     * code is safe from the object disappearing from underneath it.  (This is
1016     * the cookie passed to native_setup().)
1017     */
1018    private static void postEventFromNative(Object mediaplayer_ref,
1019                                            int what, int arg1, int arg2, Object obj)
1020    {
1021        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
1022        if (mp == null) {
1023            return;
1024        }
1025
1026        if (mp.mEventHandler != null) {
1027            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1028            mp.mEventHandler.sendMessage(m);
1029        }
1030    }
1031
1032    /**
1033     * Interface definition for a callback to be invoked when the media
1034     * source is ready for playback.
1035     */
1036    public interface OnPreparedListener
1037    {
1038        /**
1039         * Called when the media file is ready for playback.
1040         *
1041         * @param mp the MediaPlayer that is ready for playback
1042         */
1043        void onPrepared(MediaPlayer mp);
1044    }
1045
1046    /**
1047     * Register a callback to be invoked when the media source is ready
1048     * for playback.
1049     *
1050     * @param listener the callback that will be run
1051     */
1052    public void setOnPreparedListener(OnPreparedListener listener)
1053    {
1054        mOnPreparedListener = listener;
1055    }
1056
1057    private OnPreparedListener mOnPreparedListener;
1058
1059    /**
1060     * Interface definition for a callback to be invoked when playback of
1061     * a media source has completed.
1062     */
1063    public interface OnCompletionListener
1064    {
1065        /**
1066         * Called when the end of a media source is reached during playback.
1067         *
1068         * @param mp the MediaPlayer that reached the end of the file
1069         */
1070        void onCompletion(MediaPlayer mp);
1071    }
1072
1073    /**
1074     * Register a callback to be invoked when the end of a media source
1075     * has been reached during playback.
1076     *
1077     * @param listener the callback that will be run
1078     */
1079    public void setOnCompletionListener(OnCompletionListener listener)
1080    {
1081        mOnCompletionListener = listener;
1082    }
1083
1084    private OnCompletionListener mOnCompletionListener;
1085
1086    /**
1087     * Interface definition of a callback to be invoked indicating buffering
1088     * status of a media resource being streamed over the network.
1089     */
1090    public interface OnBufferingUpdateListener
1091    {
1092        /**
1093         * Called to update status in buffering a media stream.
1094         *
1095         * @param mp      the MediaPlayer the update pertains to
1096         * @param percent the percentage (0-100) of the buffer
1097         *                that has been filled thus far
1098         */
1099        void onBufferingUpdate(MediaPlayer mp, int percent);
1100    }
1101
1102    /**
1103     * Register a callback to be invoked when the status of a network
1104     * stream's buffer has changed.
1105     *
1106     * @param listener the callback that will be run.
1107     */
1108    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
1109    {
1110        mOnBufferingUpdateListener = listener;
1111    }
1112
1113    private OnBufferingUpdateListener mOnBufferingUpdateListener;
1114
1115    /**
1116     * Interface definition of a callback to be invoked indicating
1117     * the completion of a seek operation.
1118     */
1119    public interface OnSeekCompleteListener
1120    {
1121        /**
1122         * Called to indicate the completion of a seek operation.
1123         *
1124         * @param mp the MediaPlayer that issued the seek operation
1125         */
1126        public void onSeekComplete(MediaPlayer mp);
1127    }
1128
1129    /**
1130     * Register a callback to be invoked when a seek operation has been
1131     * completed.
1132     *
1133     * @param listener the callback that will be run
1134     */
1135    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
1136    {
1137        mOnSeekCompleteListener = listener;
1138    }
1139
1140    private OnSeekCompleteListener mOnSeekCompleteListener;
1141
1142    /**
1143     * Interface definition of a callback to be invoked when the
1144     * video size is first known or updated
1145     */
1146    public interface OnVideoSizeChangedListener
1147    {
1148        /**
1149         * Called to indicate the video size
1150         *
1151         * @param mp        the MediaPlayer associated with this callback
1152         * @param width     the width of the video
1153         * @param height    the height of the video
1154         */
1155        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
1156    }
1157
1158    /**
1159     * Register a callback to be invoked when the video size is
1160     * known or updated.
1161     *
1162     * @param listener the callback that will be run
1163     */
1164    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
1165    {
1166        mOnVideoSizeChangedListener = listener;
1167    }
1168
1169    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
1170
1171    /* Do not change these values without updating their counterparts
1172     * in include/media/mediaplayer.h!
1173     */
1174    /** Unspecified media player error.
1175     * @see android.media.MediaPlayer.OnErrorListener
1176     */
1177    public static final int MEDIA_ERROR_UNKNOWN = 1;
1178
1179    /** Media server died. In this case, the application must release the
1180     * MediaPlayer object and instantiate a new one.
1181     * @see android.media.MediaPlayer.OnErrorListener
1182     */
1183    public static final int MEDIA_ERROR_SERVER_DIED = 100;
1184
1185    /** The video is streamed and its container is not valid for progressive
1186     * playback i.e the video's index (e.g moov atom) is not at the start of the
1187     * file.
1188     * @see android.media.MediaPlayer.OnErrorListener
1189     */
1190    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
1191
1192    /**
1193     * Interface definition of a callback to be invoked when there
1194     * has been an error during an asynchronous operation (other errors
1195     * will throw exceptions at method call time).
1196     */
1197    public interface OnErrorListener
1198    {
1199        /**
1200         * Called to indicate an error.
1201         *
1202         * @param mp      the MediaPlayer the error pertains to
1203         * @param what    the type of error that has occurred:
1204         * <ul>
1205         * <li>{@link #MEDIA_ERROR_UNKNOWN}
1206         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
1207         * </ul>
1208         * @param extra an extra code, specific to the error. Typically
1209         * implementation dependant.
1210         * @return True if the method handled the error, false if it didn't.
1211         * Returning false, or not having an OnErrorListener at all, will
1212         * cause the OnCompletionListener to be called.
1213         */
1214        boolean onError(MediaPlayer mp, int what, int extra);
1215    }
1216
1217    /**
1218     * Register a callback to be invoked when an error has happened
1219     * during an asynchronous operation.
1220     *
1221     * @param listener the callback that will be run
1222     */
1223    public void setOnErrorListener(OnErrorListener listener)
1224    {
1225        mOnErrorListener = listener;
1226    }
1227
1228    private OnErrorListener mOnErrorListener;
1229
1230
1231    /* Do not change these values without updating their counterparts
1232     * in include/media/mediaplayer.h!
1233     */
1234    /** Unspecified media player info.
1235     * @see android.media.MediaPlayer.OnInfoListener
1236     */
1237    public static final int MEDIA_INFO_UNKNOWN = 1;
1238
1239    /** The video is too complex for the decoder: it can't decode frames fast
1240     *  enough. Possibly only the audio plays fine at this stage.
1241     * @see android.media.MediaPlayer.OnInfoListener
1242     */
1243    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
1244
1245    /** Bad interleaving means that a media has been improperly interleaved or
1246     * not interleaved at all, e.g has all the video samples first then all the
1247     * audio ones. Video is playing but a lot of disk seeks may be happening.
1248     * @see android.media.MediaPlayer.OnInfoListener
1249     */
1250    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
1251
1252    /** The media cannot be seeked (e.g live stream)
1253     * @see android.media.MediaPlayer.OnInfoListener
1254     */
1255    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
1256
1257    /**
1258     * Interface definition of a callback to be invoked to communicate some
1259     * info and/or warning about the media or its playback.
1260     */
1261    public interface OnInfoListener
1262    {
1263        /**
1264         * Called to indicate an info or a warning.
1265         *
1266         * @param mp      the MediaPlayer the info pertains to.
1267         * @param what    the type of info or warning.
1268         * <ul>
1269         * <li>{@link #MEDIA_INFO_UNKNOWN}
1270         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
1271         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
1272         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
1273         * </ul>
1274         * @param extra an extra code, specific to the info. Typically
1275         * implementation dependant.
1276         * @return True if the method handled the info, false if it didn't.
1277         * Returning false, or not having an OnErrorListener at all, will
1278         * cause the info to be discarded.
1279         */
1280        boolean onInfo(MediaPlayer mp, int what, int extra);
1281    }
1282
1283    /**
1284     * Register a callback to be invoked when an info/warning is available.
1285     *
1286     * @param listener the callback that will be run
1287     */
1288    public void setOnInfoListener(OnInfoListener listener)
1289    {
1290        mOnInfoListener = listener;
1291    }
1292
1293    private OnInfoListener mOnInfoListener;
1294}
1295