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