MediaPlayer.java revision 8b0b174198793cabb2b3fcc015f9bfdc9d5082b5
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        setDataSource(uri.toString());
621        return;
622    }
623
624    /**
625     * Sets the data source (file-path or http/rtsp URL) to use.
626     *
627     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
628     * @throws IllegalStateException if it is called in an invalid state
629     */
630    public native void setDataSource(String path) throws IOException, IllegalArgumentException, IllegalStateException;
631
632    /**
633     * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
634     * to close the file descriptor. It is safe to do so as soon as this call returns.
635     *
636     * @param fd the FileDescriptor for the file you want to play
637     * @throws IllegalStateException if it is called in an invalid state
638     */
639    public void setDataSource(FileDescriptor fd)
640            throws IOException, IllegalArgumentException, IllegalStateException {
641        // intentionally less than LONG_MAX
642        setDataSource(fd, 0, 0x7ffffffffffffffL);
643    }
644
645    /**
646     * Sets the data source (FileDescriptor) to use.  It is the caller's responsibility
647     * to close the file descriptor. It is safe to do so as soon as this call returns.
648     *
649     * @param fd the FileDescriptor for the file you want to play
650     * @param offset the offset into the file where the data to be played starts, in bytes
651     * @param length the length in bytes of the data to be played
652     * @throws IllegalStateException if it is called in an invalid state
653     */
654    public native void setDataSource(FileDescriptor fd, long offset, long length)
655            throws IOException, IllegalArgumentException, IllegalStateException;
656
657    /**
658     * Prepares the player for playback, synchronously.
659     *
660     * After setting the datasource and the display surface, you need to either
661     * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
662     * which blocks until MediaPlayer is ready for playback.
663     *
664     * @throws IllegalStateException if it is called in an invalid state
665     */
666    public native void prepare() throws IOException, IllegalStateException;
667
668    /**
669     * Prepares the player for playback, asynchronously.
670     *
671     * After setting the datasource and the display surface, you need to either
672     * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
673     * which returns immediately, rather than blocking until enough data has been
674     * buffered.
675     *
676     * @throws IllegalStateException if it is called in an invalid state
677     */
678    public native void prepareAsync() throws IllegalStateException;
679
680    /**
681     * Starts or resumes playback. If playback had previously been paused,
682     * playback will continue from where it was paused. If playback had
683     * been stopped, or never started before, playback will start at the
684     * beginning.
685     *
686     * @throws IllegalStateException if it is called in an invalid state
687     */
688    public  void start() throws IllegalStateException {
689        stayAwake(true);
690        _start();
691    }
692
693    private native void _start() throws IllegalStateException;
694
695    /**
696     * Stops playback after playback has been stopped or paused.
697     *
698     * @throws IllegalStateException if the internal player engine has not been
699     * initialized.
700     */
701    public void stop() throws IllegalStateException {
702        stayAwake(false);
703        _stop();
704    }
705
706    private native void _stop() throws IllegalStateException;
707
708    /**
709     * Pauses playback. Call start() to resume.
710     *
711     * @throws IllegalStateException if the internal player engine has not been
712     * initialized.
713     */
714    public void pause() throws IllegalStateException {
715        stayAwake(false);
716        _pause();
717    }
718
719    private native void _pause() throws IllegalStateException;
720
721    /**
722     * Set the low-level power management behavior for this MediaPlayer.  This
723     * can be used when the MediaPlayer is not playing through a SurfaceHolder
724     * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
725     * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
726     *
727     * <p>This function has the MediaPlayer access the low-level power manager
728     * service to control the device's power usage while playing is occurring.
729     * The parameter is a combination of {@link android.os.PowerManager} wake flags.
730     * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
731     * permission.
732     * By default, no attempt is made to keep the device awake during playback.
733     *
734     * @param context the Context to use
735     * @param mode    the power/wake mode to set
736     * @see android.os.PowerManager
737     */
738    public void setWakeMode(Context context, int mode) {
739        boolean washeld = false;
740        if (mWakeLock != null) {
741            if (mWakeLock.isHeld()) {
742                washeld = true;
743                mWakeLock.release();
744            }
745            mWakeLock = null;
746        }
747
748        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
749        mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
750        mWakeLock.setReferenceCounted(false);
751        if (washeld) {
752            mWakeLock.acquire();
753        }
754    }
755
756    /**
757     * Control whether we should use the attached SurfaceHolder to keep the
758     * screen on while video playback is occurring.  This is the preferred
759     * method over {@link #setWakeMode} where possible, since it doesn't
760     * require that the application have permission for low-level wake lock
761     * access.
762     *
763     * @param screenOn Supply true to keep the screen on, false to allow it
764     * to turn off.
765     */
766    public void setScreenOnWhilePlaying(boolean screenOn) {
767        if (mScreenOnWhilePlaying != screenOn) {
768            mScreenOnWhilePlaying = screenOn;
769            updateSurfaceScreenOn();
770        }
771    }
772
773    private void stayAwake(boolean awake) {
774        if (mWakeLock != null) {
775            if (awake && !mWakeLock.isHeld()) {
776                mWakeLock.acquire();
777            } else if (!awake && mWakeLock.isHeld()) {
778                mWakeLock.release();
779            }
780        }
781        mStayAwake = awake;
782        updateSurfaceScreenOn();
783    }
784
785    private void updateSurfaceScreenOn() {
786        if (mSurfaceHolder != null) {
787            mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
788        }
789    }
790
791    /**
792     * Returns the width of the video.
793     *
794     * @return the width of the video, or 0 if there is no video,
795     * no display surface was set, or prepare()/prepareAsync()
796     * have not completed yet
797     */
798    public native int getVideoWidth();
799
800    /**
801     * Returns the height of the video.
802     *
803     * @return the height of the video, or 0 if there is no video,
804     * no display surface was set, or prepare()/prepareAsync()
805     * have not completed yet
806     */
807    public native int getVideoHeight();
808
809    /**
810     * Checks whether the MediaPlayer is playing.
811     *
812     * @return true if currently playing, false otherwise
813     */
814    public native boolean isPlaying();
815
816    /**
817     * Seeks to specified time position.
818     *
819     * @param msec the offset in milliseconds from the start to seek to
820     * @throws IllegalStateException if the internal player engine has not been
821     * initialized
822     */
823    public native void seekTo(int msec) throws IllegalStateException;
824
825    /**
826     * Gets the current playback position.
827     *
828     * @return the current position in milliseconds
829     */
830    public native int getCurrentPosition();
831
832    /**
833     * Gets the duration of the file.
834     *
835     * @return the duration in milliseconds
836     */
837    public native int getDuration();
838
839    /**
840     * Releases resources associated with this MediaPlayer object.
841     * It is considered good practice to call this method when you're
842     * done using the MediaPlayer.
843     */
844    public void release() {
845        stayAwake(false);
846        updateSurfaceScreenOn();
847        mOnPreparedListener = null;
848        mOnBufferingUpdateListener = null;
849        mOnCompletionListener = null;
850        mOnSeekCompleteListener = null;
851        mOnErrorListener = null;
852        mOnInfoListener = null;
853        mOnVideoSizeChangedListener = null;
854        _release();
855    }
856
857    private native void _release();
858
859    /**
860     * Resets the MediaPlayer to its uninitialized state. After calling
861     * this method, you will have to initialize it again by setting the
862     * data source and calling prepare().
863     */
864    public void reset() {
865        stayAwake(false);
866        _reset();
867        // make sure none of the listeners get called anymore
868        mEventHandler.removeCallbacksAndMessages(null);
869    }
870
871    private native void _reset();
872
873    /**
874     * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
875     * for a list of stream types.
876     *
877     * @param streamtype the audio stream type
878     * @see android.media.AudioManager
879     */
880    public native void setAudioStreamType(int streamtype);
881
882    /**
883     * Sets the player to be looping or non-looping.
884     *
885     * @param looping whether to loop or not
886     */
887    public native void setLooping(boolean looping);
888
889    /**
890     * Checks whether the MediaPlayer is looping or non-looping.
891     *
892     * @return true if the MediaPlayer is currently looping, false otherwise
893     */
894    public native boolean isLooping();
895
896    /**
897     * Sets the volume on this player.
898     * This API is recommended for balancing the output of audio streams
899     * within an application. Unless you are writing an application to
900     * control user settings, this API should be used in preference to
901     * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
902     * a particular type. Note that the passed volume values are raw scalars.
903     * UI controls should be scaled logarithmically.
904     *
905     * @param leftVolume left volume scalar
906     * @param rightVolume right volume scalar
907     */
908    public native void setVolume(float leftVolume, float rightVolume);
909
910    /**
911     * Currently not implemented, returns null.
912     * @deprecated
913     * @hide
914     */
915    public native Bitmap getFrameAt(int msec) throws IllegalStateException;
916
917    private native final void native_setup(Object mediaplayer_this);
918    private native final void native_finalize();
919    @Override
920    protected void finalize() { native_finalize(); }
921
922    /* Do not change these values without updating their counterparts
923     * in include/media/mediaplayer.h!
924     */
925    private static final int MEDIA_NOP = 0; // interface test message
926    private static final int MEDIA_PREPARED = 1;
927    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
928    private static final int MEDIA_BUFFERING_UPDATE = 3;
929    private static final int MEDIA_SEEK_COMPLETE = 4;
930    private static final int MEDIA_SET_VIDEO_SIZE = 5;
931    private static final int MEDIA_ERROR = 100;
932    private static final int MEDIA_INFO = 200;
933
934    private class EventHandler extends Handler
935    {
936        private MediaPlayer mMediaPlayer;
937
938        public EventHandler(MediaPlayer mp, Looper looper) {
939            super(looper);
940            mMediaPlayer = mp;
941        }
942
943        @Override
944        public void handleMessage(Message msg) {
945            if (mMediaPlayer.mNativeContext == 0) {
946                Log.w(TAG, "mediaplayer went away with unhandled events");
947                return;
948            }
949            switch(msg.what) {
950            case MEDIA_PREPARED:
951                if (mOnPreparedListener != null)
952                    mOnPreparedListener.onPrepared(mMediaPlayer);
953                return;
954
955            case MEDIA_PLAYBACK_COMPLETE:
956                if (mOnCompletionListener != null)
957                    mOnCompletionListener.onCompletion(mMediaPlayer);
958                stayAwake(false);
959                return;
960
961            case MEDIA_BUFFERING_UPDATE:
962                if (mOnBufferingUpdateListener != null)
963                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
964                return;
965
966            case MEDIA_SEEK_COMPLETE:
967              if (mOnSeekCompleteListener != null)
968                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
969              return;
970
971            case MEDIA_SET_VIDEO_SIZE:
972              if (mOnVideoSizeChangedListener != null)
973                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
974              return;
975
976            case MEDIA_ERROR:
977                // For PV specific error values (msg.arg2) look in
978                // opencore/pvmi/pvmf/include/pvmf_return_codes.h
979                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
980                boolean error_was_handled = false;
981                if (mOnErrorListener != null) {
982                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
983                }
984                if (mOnCompletionListener != null && ! error_was_handled) {
985                    mOnCompletionListener.onCompletion(mMediaPlayer);
986                }
987                stayAwake(false);
988                return;
989
990            case MEDIA_INFO:
991                // For PV specific code values (msg.arg2) look in
992                // opencore/pvmi/pvmf/include/pvmf_return_codes.h
993                Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
994                if (mOnInfoListener != null) {
995                    mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
996                }
997                // No real default action so far.
998                return;
999
1000            case MEDIA_NOP: // interface test message - ignore
1001                break;
1002
1003            default:
1004                Log.e(TAG, "Unknown message type " + msg.what);
1005                return;
1006            }
1007        }
1008    }
1009
1010    /**
1011     * Called from native code when an interesting event happens.  This method
1012     * just uses the EventHandler system to post the event back to the main app thread.
1013     * We use a weak reference to the original MediaPlayer object so that the native
1014     * code is safe from the object disappearing from underneath it.  (This is
1015     * the cookie passed to native_setup().)
1016     */
1017    private static void postEventFromNative(Object mediaplayer_ref,
1018                                            int what, int arg1, int arg2, Object obj)
1019    {
1020        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
1021        if (mp == null) {
1022            return;
1023        }
1024
1025        if (mp.mEventHandler != null) {
1026            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1027            mp.mEventHandler.sendMessage(m);
1028        }
1029    }
1030
1031    /**
1032     * Interface definition for a callback to be invoked when the media
1033     * source is ready for playback.
1034     */
1035    public interface OnPreparedListener
1036    {
1037        /**
1038         * Called when the media file is ready for playback.
1039         *
1040         * @param mp the MediaPlayer that is ready for playback
1041         */
1042        void onPrepared(MediaPlayer mp);
1043    }
1044
1045    /**
1046     * Register a callback to be invoked when the media source is ready
1047     * for playback.
1048     *
1049     * @param listener the callback that will be run
1050     */
1051    public void setOnPreparedListener(OnPreparedListener listener)
1052    {
1053        mOnPreparedListener = listener;
1054    }
1055
1056    private OnPreparedListener mOnPreparedListener;
1057
1058    /**
1059     * Interface definition for a callback to be invoked when playback of
1060     * a media source has completed.
1061     */
1062    public interface OnCompletionListener
1063    {
1064        /**
1065         * Called when the end of a media source is reached during playback.
1066         *
1067         * @param mp the MediaPlayer that reached the end of the file
1068         */
1069        void onCompletion(MediaPlayer mp);
1070    }
1071
1072    /**
1073     * Register a callback to be invoked when the end of a media source
1074     * has been reached during playback.
1075     *
1076     * @param listener the callback that will be run
1077     */
1078    public void setOnCompletionListener(OnCompletionListener listener)
1079    {
1080        mOnCompletionListener = listener;
1081    }
1082
1083    private OnCompletionListener mOnCompletionListener;
1084
1085    /**
1086     * Interface definition of a callback to be invoked indicating buffering
1087     * status of a media resource being streamed over the network.
1088     */
1089    public interface OnBufferingUpdateListener
1090    {
1091        /**
1092         * Called to update status in buffering a media stream.
1093         *
1094         * @param mp      the MediaPlayer the update pertains to
1095         * @param percent the percentage (0-100) of the buffer
1096         *                that has been filled thus far
1097         */
1098        void onBufferingUpdate(MediaPlayer mp, int percent);
1099    }
1100
1101    /**
1102     * Register a callback to be invoked when the status of a network
1103     * stream's buffer has changed.
1104     *
1105     * @param listener the callback that will be run.
1106     */
1107    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
1108    {
1109        mOnBufferingUpdateListener = listener;
1110    }
1111
1112    private OnBufferingUpdateListener mOnBufferingUpdateListener;
1113
1114    /**
1115     * Interface definition of a callback to be invoked indicating
1116     * the completion of a seek operation.
1117     */
1118    public interface OnSeekCompleteListener
1119    {
1120        /**
1121         * Called to indicate the completion of a seek operation.
1122         *
1123         * @param mp the MediaPlayer that issued the seek operation
1124         */
1125        public void onSeekComplete(MediaPlayer mp);
1126    }
1127
1128    /**
1129     * Register a callback to be invoked when a seek operation has been
1130     * completed.
1131     *
1132     * @param listener the callback that will be run
1133     */
1134    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
1135    {
1136        mOnSeekCompleteListener = listener;
1137    }
1138
1139    private OnSeekCompleteListener mOnSeekCompleteListener;
1140
1141    /**
1142     * Interface definition of a callback to be invoked when the
1143     * video size is first known or updated
1144     */
1145    public interface OnVideoSizeChangedListener
1146    {
1147        /**
1148         * Called to indicate the video size
1149         *
1150         * @param mp        the MediaPlayer associated with this callback
1151         * @param width     the width of the video
1152         * @param height    the height of the video
1153         */
1154        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
1155    }
1156
1157    /**
1158     * Register a callback to be invoked when the video size is
1159     * known or updated.
1160     *
1161     * @param listener the callback that will be run
1162     */
1163    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
1164    {
1165        mOnVideoSizeChangedListener = listener;
1166    }
1167
1168    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
1169
1170    /* Do not change these values without updating their counterparts
1171     * in include/media/mediaplayer.h!
1172     */
1173    /** Unspecified media player error.
1174     * @see android.media.MediaPlayer.OnErrorListener
1175     */
1176    public static final int MEDIA_ERROR_UNKNOWN = 1;
1177
1178    /** Media server died. In this case, the application must release the
1179     * MediaPlayer object and instantiate a new one.
1180     * @see android.media.MediaPlayer.OnErrorListener
1181     */
1182    public static final int MEDIA_ERROR_SERVER_DIED = 100;
1183
1184    /** The video is streamed and its container is not valid for progressive
1185     * playback i.e the video's index (e.g moov atom) is not at the start of the
1186     * file.
1187     * @see android.media.MediaPlayer.OnErrorListener
1188     */
1189    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
1190
1191    /**
1192     * Interface definition of a callback to be invoked when there
1193     * has been an error during an asynchronous operation (other errors
1194     * will throw exceptions at method call time).
1195     */
1196    public interface OnErrorListener
1197    {
1198        /**
1199         * Called to indicate an error.
1200         *
1201         * @param mp      the MediaPlayer the error pertains to
1202         * @param what    the type of error that has occurred:
1203         * <ul>
1204         * <li>{@link #MEDIA_ERROR_UNKNOWN}
1205         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
1206         * </ul>
1207         * @param extra an extra code, specific to the error. Typically
1208         * implementation dependant.
1209         * @return True if the method handled the error, false if it didn't.
1210         * Returning false, or not having an OnErrorListener at all, will
1211         * cause the OnCompletionListener to be called.
1212         */
1213        boolean onError(MediaPlayer mp, int what, int extra);
1214    }
1215
1216    /**
1217     * Register a callback to be invoked when an error has happened
1218     * during an asynchronous operation.
1219     *
1220     * @param listener the callback that will be run
1221     */
1222    public void setOnErrorListener(OnErrorListener listener)
1223    {
1224        mOnErrorListener = listener;
1225    }
1226
1227    private OnErrorListener mOnErrorListener;
1228
1229
1230    /* Do not change these values without updating their counterparts
1231     * in include/media/mediaplayer.h!
1232     */
1233    /** Unspecified media player info.
1234     * @see android.media.MediaPlayer.OnInfoListener
1235     */
1236    public static final int MEDIA_INFO_UNKNOWN = 1;
1237
1238    /** The video is too complex for the decoder: it can't decode frames fast
1239     *  enough. Possibly only the audio plays fine at this stage.
1240     * @see android.media.MediaPlayer.OnInfoListener
1241     */
1242    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
1243
1244    /** Bad interleaving means that a media has been improperly interleaved or
1245     * not interleaved at all, e.g has all the video samples first then all the
1246     * audio ones. Video is playing but a lot of disk seeks may be happening.
1247     * @see android.media.MediaPlayer.OnInfoListener
1248     */
1249    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
1250
1251    /** The media cannot be seeked (e.g live stream)
1252     * @see android.media.MediaPlayer.OnInfoListener
1253     */
1254    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
1255
1256    /**
1257     * Interface definition of a callback to be invoked to communicate some
1258     * info and/or warning about the media or its playback.
1259     */
1260    public interface OnInfoListener
1261    {
1262        /**
1263         * Called to indicate an info or a warning.
1264         *
1265         * @param mp      the MediaPlayer the info pertains to.
1266         * @param what    the type of info or warning.
1267         * <ul>
1268         * <li>{@link #MEDIA_INFO_UNKNOWN}
1269         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
1270         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
1271         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
1272         * </ul>
1273         * @param extra an extra code, specific to the info. Typically
1274         * implementation dependant.
1275         * @return True if the method handled the info, false if it didn't.
1276         * Returning false, or not having an OnErrorListener at all, will
1277         * cause the info to be discarded.
1278         */
1279        boolean onInfo(MediaPlayer mp, int what, int extra);
1280    }
1281
1282    /**
1283     * Register a callback to be invoked when an info/warning is available.
1284     *
1285     * @param listener the callback that will be run
1286     */
1287    public void setOnInfoListener(OnInfoListener listener)
1288    {
1289        mOnInfoListener = listener;
1290    }
1291
1292    private OnInfoListener mOnInfoListener;
1293}
1294