MediaPlayer.java revision f013e1afd1e68af5e3b868c26a653bbfb39538f8
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 <a href="../widget/VideoView.html">VideoView</a>.
43 * Please see <a href="../../../toolbox/apis/media.html">Android Media APIs</a>
44 * for additional help using MediaPlayer.
45 *
46 * <p>Topics covered 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     * Sets the SurfaceHolder to use for displaying the video portion of the media.
474     * This call is optional. Not calling it when playing back a video will
475     * result in only the audio track being played.
476     *
477     * @param sh the SurfaceHolder to use for video display
478     */
479    public void setDisplay(SurfaceHolder sh) {
480        mSurfaceHolder = sh;
481        mSurface = sh.getSurface();
482        updateSurfaceScreenOn();
483    }
484
485    /**
486     * Convenience method to create a MediaPlayer for a given Uri.
487     * On success, {@link #prepare()} will already have been called and must not be called again.
488     * <p>When done with the MediaPlayer, you should call  {@link #release()},
489     * to free the resources. If not released, too many MediaPlayer instances will
490     * result in an exception.</p>
491     *
492     * @param context the Context to use
493     * @param uri the Uri from which to get the datasource
494     * @return a MediaPlayer object, or null if creation failed
495     */
496    public static MediaPlayer create(Context context, Uri uri) {
497        return create (context, uri, null);
498    }
499
500    /**
501     * Convenience method to create a MediaPlayer for a given Uri.
502     * On success, {@link #prepare()} will already have been called and must not be called again.
503     * <p>When done with the MediaPlayer, you should call  {@link #release()},
504     * to free the resources. If not released, too many MediaPlayer instances will
505     * result in an exception.</p>
506     *
507     * @param context the Context to use
508     * @param uri the Uri from which to get the datasource
509     * @param holder the SurfaceHolder to use for displaying the video
510     * @return a MediaPlayer object, or null if creation failed
511     */
512    public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
513
514        try {
515            MediaPlayer mp = new MediaPlayer();
516            mp.setDataSource(context, uri);
517            if (holder != null) {
518                mp.setDisplay(holder);
519            }
520            mp.prepare();
521            return mp;
522        } catch (IOException ex) {
523            Log.d(TAG, "create failed:", ex);
524            // fall through
525        } catch (IllegalArgumentException ex) {
526            Log.d(TAG, "create failed:", ex);
527            // fall through
528        } catch (SecurityException ex) {
529            Log.d(TAG, "create failed:", ex);
530            // fall through
531        }
532
533        return null;
534    }
535
536    /**
537     * Convenience method to create a MediaPlayer for a given resource id.
538     * On success, {@link #prepare()} will already have been called and must not be called again.
539     * <p>When done with the MediaPlayer, you should call  {@link #release()},
540     * to free the resources. If not released, too many MediaPlayer instances will
541     * result in an exception.</p>
542     *
543     * @param context the Context to use
544     * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
545     *              the resource to use as the datasource
546     * @return a MediaPlayer object, or null if creation failed
547     */
548    public static MediaPlayer create(Context context, int resid) {
549        try {
550            AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
551            if (afd == null) return null;
552
553            MediaPlayer mp = new MediaPlayer();
554            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
555            afd.close();
556            mp.prepare();
557            return mp;
558        } catch (IOException ex) {
559            Log.d(TAG, "create failed:", ex);
560            // fall through
561        } catch (IllegalArgumentException ex) {
562            Log.d(TAG, "create failed:", ex);
563           // fall through
564        } catch (SecurityException ex) {
565            Log.d(TAG, "create failed:", ex);
566            // fall through
567        }
568        return null;
569    }
570
571    /**
572     * Sets the data source as a content Uri.
573     *
574     * @param context the Context to use when resolving the Uri
575     * @param uri the Content URI of the data you want to play
576     * @throws IllegalStateException if it is called in an invalid state
577     */
578    public void setDataSource(Context context, Uri uri)
579        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
580
581        String scheme = uri.getScheme();
582        if(scheme == null || scheme.equals("file")) {
583            setDataSource(uri.getPath());
584            return;
585        }
586
587        ParcelFileDescriptor fd = null;
588        try {
589            ContentResolver resolver = context.getContentResolver();
590            fd = resolver.openFileDescriptor(uri, "r");
591            if (fd == null) {
592                return;
593            }
594            setDataSource(fd.getFileDescriptor());
595            return;
596        } catch (SecurityException ex) {
597        } catch (IOException ex) {
598        } finally {
599            if (fd != null) {
600                fd.close();
601            }
602        }
603        setDataSource(uri.toString());
604        return;
605    }
606
607    /**
608     * Sets the data source (file-path or http/rtsp URL) to use.
609     *
610     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
611     * @throws IllegalStateException if it is called in an invalid state
612     */
613    public native void setDataSource(String path) throws IOException, IllegalArgumentException, IllegalStateException;
614
615    /**
616     * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
617     * to close the file descriptor. It is safe to do so as soon as this call returns.
618     *
619     * @param fd the FileDescriptor for the file you want to play
620     * @throws IllegalStateException if it is called in an invalid state
621     */
622    public void setDataSource(FileDescriptor fd)
623            throws IOException, IllegalArgumentException, IllegalStateException {
624        // intentionally less than LONG_MAX
625        setDataSource(fd, 0, 0x7ffffffffffffffL);
626    }
627
628    /**
629     * Sets the data source (FileDescriptor) to use.  It is the caller's responsibility
630     * to close the file descriptor. It is safe to do so as soon as this call returns.
631     *
632     * @param fd the FileDescriptor for the file you want to play
633     * @param offset the offset into the file where the data to be played starts, in bytes
634     * @param length the length in bytes of the data to be played
635     * @throws IllegalStateException if it is called in an invalid state
636     */
637    public native void setDataSource(FileDescriptor fd, long offset, long length)
638            throws IOException, IllegalArgumentException, IllegalStateException;
639
640    /**
641     * Prepares the player for playback, synchronously.
642     *
643     * After setting the datasource and the display surface, you need to either
644     * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
645     * which blocks until MediaPlayer is ready for playback.
646     *
647     * @throws IllegalStateException if it is called in an invalid state
648     */
649    public native void prepare() throws IOException, IllegalStateException;
650
651    /**
652     * Prepares the player for playback, asynchronously.
653     *
654     * After setting the datasource and the display surface, you need to either
655     * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
656     * which returns immediately, rather than blocking until enough data has been
657     * buffered.
658     *
659     * @throws IllegalStateException if it is called in an invalid state
660     */
661    public native void prepareAsync() throws IllegalStateException;
662
663    /**
664     * Starts or resumes playback. If playback had previously been paused,
665     * playback will continue from where it was paused. If playback had
666     * been stopped, or never started before, playback will start at the
667     * beginning.
668     *
669     * @throws IllegalStateException if it is called in an invalid state
670     */
671    public  void start() throws IllegalStateException {
672        stayAwake(true);
673        _start();
674    }
675
676    private native void _start() throws IllegalStateException;
677
678    /**
679     * Stops playback after playback has been stopped or paused.
680     *
681     * @throws IllegalStateException if the internal player engine has not been
682     * initialized.
683     */
684    public void stop() throws IllegalStateException {
685        stayAwake(false);
686        _stop();
687    }
688
689    private native void _stop() throws IllegalStateException;
690
691    /**
692     * Pauses playback. Call start() to resume.
693     *
694     * @throws IllegalStateException if the internal player engine has not been
695     * initialized.
696     */
697    public void pause() throws IllegalStateException {
698        stayAwake(false);
699        _pause();
700    }
701
702    private native void _pause() throws IllegalStateException;
703
704    /**
705     * Set the low-level power management behavior for this MediaPlayer.  This
706     * can be used when the MediaPlayer is not playing through a SurfaceHolder
707     * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
708     * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
709     *
710     * <p>This function has the MediaPlayer access the low-level power manager
711     * service to control the device's power usage while playing is occurring.
712     * The parameter is a combination of {@link android.os.PowerManager} wake flags.
713     * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
714     * permission.
715     * By default, no attempt is made to keep the device awake during playback.
716     *
717     * @param context the Context to use
718     * @param mode    the power/wake mode to set
719     * @see android.os.PowerManager
720     */
721    public void setWakeMode(Context context, int mode) {
722        boolean washeld = false;
723        if (mWakeLock != null) {
724            if (mWakeLock.isHeld()) {
725                washeld = true;
726                mWakeLock.release();
727            }
728            mWakeLock = null;
729        }
730
731        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
732        mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
733        mWakeLock.setReferenceCounted(false);
734        if (washeld) {
735            mWakeLock.acquire();
736        }
737    }
738
739    /**
740     * Control whether we should use the attached SurfaceHolder to keep the
741     * screen on while video playback is occurring.  This is the preferred
742     * method over {@link #setWakeMode} where possible, since it doesn't
743     * require that the application have permission for low-level wake lock
744     * access.
745     *
746     * @param screenOn Supply true to keep the screen on, false to allow it
747     * to turn off.
748     */
749    public void setScreenOnWhilePlaying(boolean screenOn) {
750        if (mScreenOnWhilePlaying != screenOn) {
751            mScreenOnWhilePlaying = screenOn;
752            updateSurfaceScreenOn();
753        }
754    }
755
756    private void stayAwake(boolean awake) {
757        if (mWakeLock != null) {
758            if (awake && !mWakeLock.isHeld()) {
759                mWakeLock.acquire();
760            } else if (!awake && mWakeLock.isHeld()) {
761                mWakeLock.release();
762            }
763        }
764        mStayAwake = awake;
765        updateSurfaceScreenOn();
766    }
767
768    private void updateSurfaceScreenOn() {
769        if (mSurfaceHolder != null) {
770            mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
771        }
772    }
773
774    /**
775     * Returns the width of the video.
776     *
777     * @return the width of the video, or 0 if there is no video,
778     * no display surface was set, or prepare()/prepareAsync()
779     * have not completed yet
780     */
781    public native int getVideoWidth();
782
783    /**
784     * Returns the height of the video.
785     *
786     * @return the height of the video, or 0 if there is no video,
787     * no display surface was set, or prepare()/prepareAsync()
788     * have not completed yet
789     */
790    public native int getVideoHeight();
791
792    /**
793     * Checks whether the MediaPlayer is playing.
794     *
795     * @return true if currently playing, false otherwise
796     */
797    public native boolean isPlaying();
798
799    /**
800     * Seeks to specified time position.
801     *
802     * @param msec the offset in milliseconds from the start to seek to
803     * @throws IllegalStateException if the internal player engine has not been
804     * initialized
805     */
806    public native void seekTo(int msec) throws IllegalStateException;
807
808    /**
809     * Gets the current playback position.
810     *
811     * @return the current position in milliseconds
812     */
813    public native int getCurrentPosition();
814
815    /**
816     * Gets the duration of the file.
817     *
818     * @return the duration in milliseconds
819     */
820    public native int getDuration();
821
822    /**
823     * Releases resources associated with this MediaPlayer object.
824     * It is considered good practice to call this method when you're
825     * done using the MediaPlayer.
826     */
827    public void release() {
828        if (mWakeLock != null) mWakeLock.release();
829        updateSurfaceScreenOn();
830        mOnPreparedListener = null;
831        mOnBufferingUpdateListener = null;
832        mOnCompletionListener = null;
833        mOnSeekCompleteListener = null;
834        mOnErrorListener = null;
835        mOnVideoSizeChangedListener = null;
836        _release();
837    }
838
839    private native void _release();
840
841    /**
842     * Resets the MediaPlayer to its uninitialized state. After calling
843     * this method, you will have to initialize it again by setting the
844     * data source and calling prepare().
845     */
846    public void reset() {
847        _reset();
848        // make sure none of the listeners get called anymore
849        mEventHandler.removeCallbacksAndMessages(null);
850    }
851
852    private native void _reset();
853
854    /**
855     * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
856     * for a list of stream types.
857     *
858     * @param streamtype the audio stream type
859     * @see android.media.AudioManager
860     */
861    public native void setAudioStreamType(int streamtype);
862
863    /**
864     * Sets the player to be looping or non-looping.
865     *
866     * @param looping whether to loop or not
867     */
868    public native void setLooping(boolean looping);
869
870    /**
871     * Checks whether the MediaPlayer is looping or non-looping.
872     *
873     * @return true if the MediaPlayer is currently looping, false otherwise
874     */
875    public native boolean isLooping();
876
877    /**
878     * Sets the volume on this player.
879     * This API is recommended for balancing the output of audio streams
880     * within an application. Unless you are writing an application to
881     * control user settings, this API should be used in preference to
882     * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
883     * a particular type. Note that the passed volume values are raw scalars.
884     * UI controls should be scaled logarithmically.
885     *
886     * @param leftVolume left volume scalar
887     * @param rightVolume right volume scalar
888     */
889    public native void setVolume(float leftVolume, float rightVolume);
890
891    /**
892     * Currently not implemented, returns null.
893     * @deprecated
894     * @hide
895     */
896    public native Bitmap getFrameAt(int msec) throws IllegalStateException;
897
898    private native final void native_setup(Object mediaplayer_this);
899    private native final void native_finalize();
900    @Override
901    protected void finalize() { native_finalize(); }
902
903    /* Do not change these values without updating their counterparts
904     * in include/media/mediaplayer.h!
905     */
906    private static final int MEDIA_NOP = 0; // interface test message
907    private static final int MEDIA_PREPARED = 1;
908    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
909    private static final int MEDIA_BUFFERING_UPDATE = 3;
910    private static final int MEDIA_SEEK_COMPLETE = 4;
911    private static final int MEDIA_SET_VIDEO_SIZE = 5;
912    private static final int MEDIA_ERROR = 100;
913
914    // error codes from framework that indicate content issues
915    // contained in arg1 of error message
916
917    // Seek not supported - live stream
918    private static final int ERROR_SEEK_NOT_SUPPORTED = 42;
919
920    // A/V interleave exceeds the progressive streaming buffer
921    private static final int ERROR_CONTENT_IS_POORLY_INTERLEAVED = 43;
922
923    // video decoder is falling behind - content is too complex
924    private static final int ERROR_VIDEO_TRACK_IS_FALLING_BEHIND = 44;
925
926    private class EventHandler extends Handler
927    {
928        private MediaPlayer mMediaPlayer;
929
930        public EventHandler(MediaPlayer mp, Looper looper) {
931            super(looper);
932            mMediaPlayer = mp;
933        }
934
935        @Override
936        public void handleMessage(Message msg) {
937            if (mMediaPlayer.mNativeContext == 0) {
938                Log.w(TAG, "mediaplayer went away with unhandled events");
939                return;
940            }
941            switch(msg.what) {
942            case MEDIA_PREPARED:
943                if (mOnPreparedListener != null)
944                    mOnPreparedListener.onPrepared(mMediaPlayer);
945                return;
946
947            case MEDIA_PLAYBACK_COMPLETE:
948                if (mOnCompletionListener != null)
949                    mOnCompletionListener.onCompletion(mMediaPlayer);
950                stayAwake(false);
951                return;
952
953            case MEDIA_BUFFERING_UPDATE:
954                if (mOnBufferingUpdateListener != null)
955                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
956                return;
957
958            case MEDIA_SEEK_COMPLETE:
959              if (mOnSeekCompleteListener != null)
960                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
961              return;
962
963            case MEDIA_SET_VIDEO_SIZE:
964              if (mOnVideoSizeChangedListener != null)
965                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
966              return;
967
968            case MEDIA_ERROR:
969                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
970                boolean error_was_handled = false;
971                if (mOnErrorListener != null) {
972                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
973                }
974                if (mOnCompletionListener != null && ! error_was_handled) {
975                    mOnCompletionListener.onCompletion(mMediaPlayer);
976                }
977                stayAwake(false);
978                return;
979            case MEDIA_NOP: // interface test message - ignore
980                break;
981
982            default:
983                Log.e(TAG, "Unknown message type " + msg.what);
984                return;
985            }
986        }
987    }
988
989    /**
990     * Called from native code when an interesting event happens.  This method
991     * just uses the EventHandler system to post the event back to the main app thread.
992     * We use a weak reference to the original MediaPlayer object so that the native
993     * code is safe from the object disappearing from underneath it.  (This is
994     * the cookie passed to native_setup().)
995     */
996    private static void postEventFromNative(Object mediaplayer_ref,
997                                            int what, int arg1, int arg2, Object obj)
998    {
999        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
1000        if (mp == null) {
1001            return;
1002        }
1003
1004        if (mp.mEventHandler != null) {
1005            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1006            mp.mEventHandler.sendMessage(m);
1007        }
1008    }
1009
1010    /**
1011     * Interface definition for a callback to be invoked when the media
1012     * source is ready for playback.
1013     */
1014    public interface OnPreparedListener
1015    {
1016        /**
1017         * Called when the media file is ready for playback.
1018         *
1019         * @param mp the MediaPlayer that is ready for playback
1020         */
1021        void onPrepared(MediaPlayer mp);
1022    }
1023
1024    /**
1025     * Register a callback to be invoked when the media source is ready
1026     * for playback.
1027     *
1028     * @param l the callback that will be run
1029     */
1030    public void setOnPreparedListener(OnPreparedListener l)
1031    {
1032        mOnPreparedListener = l;
1033    }
1034
1035    private OnPreparedListener mOnPreparedListener;
1036
1037    /**
1038     * Interface definition for a callback to be invoked when playback of
1039     * a media source has completed.
1040     */
1041    public interface OnCompletionListener
1042    {
1043        /**
1044         * Called when the end of a media source is reached during playback.
1045         *
1046         * @param mp the MediaPlayer that reached the end of the file
1047         */
1048        void onCompletion(MediaPlayer mp);
1049    }
1050
1051    /**
1052     * Register a callback to be invoked when the end of a media source
1053     * has been reached during playback.
1054     *
1055     * @param l the callback that will be run
1056     */
1057    public void setOnCompletionListener(OnCompletionListener l)
1058    {
1059        mOnCompletionListener = l;
1060    }
1061
1062    private OnCompletionListener mOnCompletionListener;
1063
1064    /**
1065     * Interface definition of a callback to be invoked indicating buffering
1066     * status of a media resource being streamed over the network.
1067     */
1068    public interface OnBufferingUpdateListener
1069    {
1070        /**
1071         * Called to update status in buffering a media stream.
1072         *
1073         * @param mp      the MediaPlayer the update pertains to
1074         * @param percent the percentage (0-100) of the buffer
1075         *                that has been filled thus far
1076         */
1077        void onBufferingUpdate(MediaPlayer mp, int percent);
1078    }
1079
1080    /**
1081     * Register a callback to be invoked when the status of a network
1082     * stream's buffer has changed.
1083     *
1084     * @param l the callback that will be run
1085     */
1086    public void setOnBufferingUpdateListener(OnBufferingUpdateListener l)
1087    {
1088        mOnBufferingUpdateListener = l;
1089    }
1090
1091    private OnBufferingUpdateListener mOnBufferingUpdateListener;
1092
1093    /**
1094     * Interface definition of a callback to be invoked indicating
1095     * the completion of a seek operation.
1096     */
1097    public interface OnSeekCompleteListener
1098    {
1099        /**
1100         * Called to indicate the completion of a seek operation.
1101         *
1102         * @param mp the MediaPlayer that issued the seek operation
1103         */
1104        public void onSeekComplete(MediaPlayer mp);
1105    }
1106
1107    /**
1108     * Register a callback to be invoked when a seek operation has been
1109     * completed.
1110     *
1111     * @param l the callback that will be run
1112     */
1113    public void setOnSeekCompleteListener(OnSeekCompleteListener l)
1114    {
1115        mOnSeekCompleteListener = l;
1116    }
1117
1118    private OnSeekCompleteListener mOnSeekCompleteListener;
1119
1120    /**
1121     * Interface definition of a callback to be invoked when the
1122     * video size is first known or updated
1123     * FIXME: Unhide this API after approval
1124     * @hide
1125     */
1126    public interface OnVideoSizeChangedListener
1127    {
1128        /**
1129         * Called to indicate the video size
1130         *
1131         * @param mp        the MediaPlayer associated with this callback
1132         * @param width     the width of the video
1133         * @param height    the height of the video
1134         * @hide
1135         */
1136        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
1137    }
1138
1139    /**
1140     * Register a callback to be invoked when the video size is
1141     * known or updated.
1142     *
1143     * @param l the callback that will be run
1144     * @hide
1145     */
1146    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener l)
1147    {
1148        mOnVideoSizeChangedListener = l;
1149    }
1150
1151    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
1152
1153    /* Do not change these values without updating their counterparts
1154     * in include/media/mediaplayer.h!
1155     */
1156    /** Unspecified media player error.
1157     * @see android.media.MediaPlayer.OnErrorListener
1158     */
1159    public static final int MEDIA_ERROR_UNKNOWN = 1;
1160    /** Media server died. In this case, the application must release the
1161     * MediaPlayer object and instantiate a new one.
1162     * @see android.media.MediaPlayer.OnErrorListener
1163     */
1164    public static final int MEDIA_ERROR_SERVER_DIED = 100;
1165
1166
1167    /**
1168     * Interface definition of a callback to be invoked when there
1169     * has been an error during an asynchronous operation (other errors
1170     * will throw exceptions at method call time).
1171     */
1172    public interface OnErrorListener
1173    {
1174        /**
1175         * Called to indicate an error.
1176         *
1177         * @param mp      the MediaPlayer the error pertains to
1178         * @param what    the type of error that has occurred:
1179         * <ul>
1180         * <li>{@link #MEDIA_ERROR_UNKNOWN}
1181         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
1182         * </ul>
1183         * @param extra   an extra code, specific to the error type
1184         * @return True if the method handled the error, false if it didn't.
1185         * Returning false, or not having an OnErrorListener at all, will
1186         * cause the OnCompletionListener to be called.
1187         */
1188        boolean onError(MediaPlayer mp, int what, int extra);
1189    }
1190
1191    /**
1192     * Register a callback to be invoked when an error has happened
1193     * during an asynchronous operation.
1194     *
1195     * @param l the callback that will be run
1196     */
1197    public void setOnErrorListener(OnErrorListener l)
1198    {
1199        mOnErrorListener = l;
1200    }
1201
1202    private OnErrorListener mOnErrorListener;
1203}
1204