MediaPlayer.java revision 619346f902241736d933657a4fe10f10c50a1ba8
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.Parcel; 27import android.os.ParcelFileDescriptor; 28import android.os.PowerManager; 29import android.util.Log; 30import android.view.Surface; 31import android.view.SurfaceHolder; 32import android.graphics.Bitmap; 33import android.media.AudioManager; 34 35import java.io.FileDescriptor; 36import java.io.IOException; 37import java.util.Map; 38import java.util.Set; 39import java.lang.ref.WeakReference; 40 41/** 42 * MediaPlayer class can be used to control playback 43 * of audio/video files and streams. An example on how to use the methods in 44 * this class can be found in {@link android.widget.VideoView}. 45 * Please see <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a> 46 * for additional help using MediaPlayer. 47 * 48 * <p>Topics covered here are: 49 * <ol> 50 * <li><a href="#StateDiagram">State Diagram</a> 51 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a> 52 * <li><a href="#Permissions">Permissions</a> 53 * </ol> 54 * 55 * <a name="StateDiagram"></a> 56 * <h3>State Diagram</h3> 57 * 58 * <p>Playback control of audio/video files and streams is managed as a state 59 * machine. The following diagram shows the life cycle and the states of a 60 * MediaPlayer object driven by the supported playback control operations. 61 * The ovals represent the states a MediaPlayer object may reside 62 * in. The arcs represent the playback control operations that drive the object 63 * state transition. There are two types of arcs. The arcs with a single arrow 64 * head represent synchronous method calls, while those with 65 * a double arrow head represent asynchronous method calls.</p> 66 * 67 * <p><img src="../../../images/mediaplayer_state_diagram.gif" 68 * alt="MediaPlayer State diagram" 69 * border="0" /></p> 70 * 71 * <p>From this state diagram, one can see that a MediaPlayer object has the 72 * following states:</p> 73 * <ul> 74 * <li>When a MediaPlayer object is just created using <code>new</code> or 75 * after {@link #reset()} is called, it is in the <em>Idle</em> state; and after 76 * {@link #release()} is called, it is in the <em>End</em> state. Between these 77 * two states is the life cycle of the MediaPlayer object. 78 * <ul> 79 * <li>There is a subtle but important difference between a newly constructed 80 * MediaPlayer object and the MediaPlayer object after {@link #reset()} 81 * is called. It is a programming error to invoke methods such 82 * as {@link #getCurrentPosition()}, 83 * {@link #getDuration()}, {@link #getVideoHeight()}, 84 * {@link #getVideoWidth()}, {@link #setAudioStreamType(int)}, 85 * {@link #setLooping(boolean)}, 86 * {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()}, 87 * {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or 88 * {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these 89 * methods is called right after a MediaPlayer object is constructed, 90 * the user supplied callback method OnErrorListener.onError() won't be 91 * called by the internal player engine and the object state remains 92 * unchanged; but if these methods are called right after {@link #reset()}, 93 * the user supplied callback method OnErrorListener.onError() will be 94 * invoked by the internal player engine and the object will be 95 * transfered to the <em>Error</em> state. </li> 96 * <li>It is also recommended that once 97 * a MediaPlayer object is no longer being used, call {@link #release()} immediately 98 * so that resources used by the internal player engine associated with the 99 * MediaPlayer object can be released immediately. Resource may include 100 * singleton resources such as hardware acceleration components and 101 * failure to call {@link #release()} may cause subsequent instances of 102 * MediaPlayer objects to fallback to software implementations or fail 103 * altogether. Once the MediaPlayer 104 * object is in the <em>End</em> state, it can no longer be used and 105 * there is no way to bring it back to any other state. </li> 106 * <li>Furthermore, 107 * the MediaPlayer objects created using <code>new</code> is in the 108 * <em>Idle</em> state, while those created with one 109 * of the overloaded convenient <code>create</code> methods are <em>NOT</em> 110 * in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em> 111 * state if the creation using <code>create</code> method is successful. 112 * </li> 113 * </ul> 114 * </li> 115 * <li>In general, some playback control operation may fail due to various 116 * reasons, such as unsupported audio/video format, poorly interleaved 117 * audio/video, resolution too high, streaming timeout, and the like. 118 * Thus, error reporting and recovery is an important concern under 119 * these circumstances. Sometimes, due to programming errors, invoking a playback 120 * control operation in an invalid state may also occur. Under all these 121 * error conditions, the internal player engine invokes a user supplied 122 * OnErrorListener.onError() method if an OnErrorListener has been 123 * registered beforehand via 124 * {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}. 125 * <ul> 126 * <li>It is important to note that once an error occurs, the 127 * MediaPlayer object enters the <em>Error</em> state (except as noted 128 * above), even if an error listener has not been registered by the application.</li> 129 * <li>In order to reuse a MediaPlayer object that is in the <em> 130 * Error</em> state and recover from the error, 131 * {@link #reset()} can be called to restore the object to its <em>Idle</em> 132 * state.</li> 133 * <li>It is good programming practice to have your application 134 * register a OnErrorListener to look out for error notifications from 135 * the internal player engine.</li> 136 * <li>IllegalStateException is 137 * thrown to prevent programming errors such as calling {@link #prepare()}, 138 * {@link #prepareAsync()}, or one of the overloaded <code>setDataSource 139 * </code> methods in an invalid state. </li> 140 * </ul> 141 * </li> 142 * <li>Calling 143 * {@link #setDataSource(FileDescriptor)}, or 144 * {@link #setDataSource(String)}, or 145 * {@link #setDataSource(Context, Uri)}, or 146 * {@link #setDataSource(FileDescriptor, long, long)} transfers a 147 * MediaPlayer object in the <em>Idle</em> state to the 148 * <em>Initialized</em> state. 149 * <ul> 150 * <li>An IllegalStateException is thrown if 151 * setDataSource() is called in any other state.</li> 152 * <li>It is good programming 153 * practice to always look out for <code>IllegalArgumentException</code> 154 * and <code>IOException</code> that may be thrown from the overloaded 155 * <code>setDataSource</code> methods.</li> 156 * </ul> 157 * </li> 158 * <li>A MediaPlayer object must first enter the <em>Prepared</em> state 159 * before playback can be started. 160 * <ul> 161 * <li>There are two ways (synchronous vs. 162 * asynchronous) that the <em>Prepared</em> state can be reached: 163 * either a call to {@link #prepare()} (synchronous) which 164 * transfers the object to the <em>Prepared</em> state once the method call 165 * returns, or a call to {@link #prepareAsync()} (asynchronous) which 166 * first transfers the object to the <em>Preparing</em> state after the 167 * call returns (which occurs almost right way) while the internal 168 * player engine continues working on the rest of preparation work 169 * until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns, 170 * the internal player engine then calls a user supplied callback method, 171 * onPrepared() of the OnPreparedListener interface, if an 172 * OnPreparedListener is registered beforehand via {@link 173 * #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li> 174 * <li>It is important to note that 175 * the <em>Preparing</em> state is a transient state, and the behavior 176 * of calling any method with side effect while a MediaPlayer object is 177 * in the <em>Preparing</em> state is undefined.</li> 178 * <li>An IllegalStateException is 179 * thrown if {@link #prepare()} or {@link #prepareAsync()} is called in 180 * any other state.</li> 181 * <li>While in the <em>Prepared</em> state, properties 182 * such as audio/sound volume, screenOnWhilePlaying, looping can be 183 * adjusted by invoking the corresponding set methods.</li> 184 * </ul> 185 * </li> 186 * <li>To start the playback, {@link #start()} must be called. After 187 * {@link #start()} returns successfully, the MediaPlayer object is in the 188 * <em>Started</em> state. {@link #isPlaying()} can be called to test 189 * whether the MediaPlayer object is in the <em>Started</em> state. 190 * <ul> 191 * <li>While in the <em>Started</em> state, the internal player engine calls 192 * a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback 193 * method if a OnBufferingUpdateListener has been registered beforehand 194 * via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}. 195 * This callback allows applications to keep track of the buffering status 196 * while streaming audio/video.</li> 197 * <li>Calling {@link #start()} has not effect 198 * on a MediaPlayer object that is already in the <em>Started</em> state.</li> 199 * </ul> 200 * </li> 201 * <li>Playback can be paused and stopped, and the current playback position 202 * can be adjusted. Playback can be paused via {@link #pause()}. When the call to 203 * {@link #pause()} returns, the MediaPlayer object enters the 204 * <em>Paused</em> state. Note that the transition from the <em>Started</em> 205 * state to the <em>Paused</em> state and vice versa happens 206 * asynchronously in the player engine. It may take some time before 207 * the state is updated in calls to {@link #isPlaying()}, and it can be 208 * a number of seconds in the case of streamed content. 209 * <ul> 210 * <li>Calling {@link #start()} to resume playback for a paused 211 * MediaPlayer object, and the resumed playback 212 * position is the same as where it was paused. When the call to 213 * {@link #start()} returns, the paused MediaPlayer object goes back to 214 * the <em>Started</em> state.</li> 215 * <li>Calling {@link #pause()} has no effect on 216 * a MediaPlayer object that is already in the <em>Paused</em> state.</li> 217 * </ul> 218 * </li> 219 * <li>Calling {@link #stop()} stops playback and causes a 220 * MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared 221 * </em> or <em>PlaybackCompleted</em> state to enter the 222 * <em>Stopped</em> state. 223 * <ul> 224 * <li>Once in the <em>Stopped</em> state, playback cannot be started 225 * until {@link #prepare()} or {@link #prepareAsync()} are called to set 226 * the MediaPlayer object to the <em>Prepared</em> state again.</li> 227 * <li>Calling {@link #stop()} has no effect on a MediaPlayer 228 * object that is already in the <em>Stopped</em> state.</li> 229 * </ul> 230 * </li> 231 * <li>The playback position can be adjusted with a call to 232 * {@link #seekTo(int)}. 233 * <ul> 234 * <li>Although the asynchronuous {@link #seekTo(int)} 235 * call returns right way, the actual seek operation may take a while to 236 * finish, especially for audio/video being streamed. When the actual 237 * seek operation completes, the internal player engine calls a user 238 * supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener 239 * has been registered beforehand via 240 * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li> 241 * <li>Please 242 * note that {@link #seekTo(int)} can also be called in the other states, 243 * such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted 244 * </em> state.</li> 245 * <li>Furthermore, the actual current playback position 246 * can be retrieved with a call to {@link #getCurrentPosition()}, which 247 * is helpful for applications such as a Music player that need to keep 248 * track of the playback progress.</li> 249 * </ul> 250 * </li> 251 * <li>When the playback reaches the end of stream, the playback completes. 252 * <ul> 253 * <li>If the looping mode was being set to <var>true</var>with 254 * {@link #setLooping(boolean)}, the MediaPlayer object shall remain in 255 * the <em>Started</em> state.</li> 256 * <li>If the looping mode was set to <var>false 257 * </var>, the player engine calls a user supplied callback method, 258 * OnCompletion.onCompletion(), if a OnCompletionListener is registered 259 * beforehand via {@link #setOnCompletionListener(OnCompletionListener)}. 260 * The invoke of the callback signals that the object is now in the <em> 261 * PlaybackCompleted</em> state.</li> 262 * <li>While in the <em>PlaybackCompleted</em> 263 * state, calling {@link #start()} can restart the playback from the 264 * beginning of the audio/video source.</li> 265 * </ul> 266 * 267 * 268 * <a name="Valid_and_Invalid_States"></a> 269 * <h3>Valid and invalid states</h3> 270 * 271 * <table border="0" cellspacing="0" cellpadding="0"> 272 * <tr><td>Method Name </p></td> 273 * <td>Valid Sates </p></td> 274 * <td>Invalid States </p></td> 275 * <td>Comments </p></td></tr> 276 * <tr><td>getCurrentPosition </p></td> 277 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped, 278 * PlaybackCompleted} </p></td> 279 * <td>{Error}</p></td> 280 * <td>Successful invoke of this method in a valid state does not change the 281 * state. Calling this method in an invalid state transfers the object 282 * to the <em>Error</em> state. </p></td></tr> 283 * <tr><td>getDuration </p></td> 284 * <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td> 285 * <td>{Idle, Initialized, Error} </p></td> 286 * <td>Successful invoke of this method in a valid state does not change the 287 * state. Calling this method in an invalid state transfers the object 288 * to the <em>Error</em> state. </p></td></tr> 289 * <tr><td>getVideoHeight </p></td> 290 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped, 291 * PlaybackCompleted}</p></td> 292 * <td>{Error}</p></td> 293 * <td>Successful invoke of this method in a valid state does not change the 294 * state. Calling this method in an invalid state transfers the object 295 * to the <em>Error</em> state. </p></td></tr> 296 * <tr><td>getVideoWidth </p></td> 297 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped, 298 * PlaybackCompleted}</p></td> 299 * <td>{Error}</p></td> 300 * <td>Successful invoke of this method in a valid state does not change 301 * the state. Calling this method in an invalid state transfers the 302 * object to the <em>Error</em> state. </p></td></tr> 303 * <tr><td>isPlaying </p></td> 304 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped, 305 * PlaybackCompleted}</p></td> 306 * <td>{Error}</p></td> 307 * <td>Successful invoke of this method in a valid state does not change 308 * the state. Calling this method in an invalid state transfers the 309 * object to the <em>Error</em> state. </p></td></tr> 310 * <tr><td>pause </p></td> 311 * <td>{Started, Paused}</p></td> 312 * <td>{Idle, Initialized, Prepared, Stopped, PlaybackCompleted, Error}</p></td> 313 * <td>Successful invoke of this method in a valid state transfers the 314 * object to the <em>Paused</em> state. Calling this method in an 315 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr> 316 * <tr><td>prepare </p></td> 317 * <td>{Initialized, Stopped} </p></td> 318 * <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td> 319 * <td>Successful invoke of this method in a valid state transfers the 320 * object to the <em>Prepared</em> state. Calling this method in an 321 * invalid state throws an IllegalStateException.</p></td></tr> 322 * <tr><td>prepareAsync </p></td> 323 * <td>{Initialized, Stopped} </p></td> 324 * <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td> 325 * <td>Successful invoke of this method in a valid state transfers the 326 * object to the <em>Preparing</em> state. Calling this method in an 327 * invalid state throws an IllegalStateException.</p></td></tr> 328 * <tr><td>release </p></td> 329 * <td>any </p></td> 330 * <td>{} </p></td> 331 * <td>After {@link #release()}, the object is no longer available. </p></td></tr> 332 * <tr><td>reset </p></td> 333 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped, 334 * PlaybackCompleted, Error}</p></td> 335 * <td>{}</p></td> 336 * <td>After {@link #reset()}, the object is like being just created.</p></td></tr> 337 * <tr><td>seekTo </p></td> 338 * <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td> 339 * <td>{Idle, Initialized, Stopped, Error}</p></td> 340 * <td>Successful invoke of this method in a valid state does not change 341 * the state. Calling this method in an invalid state transfers the 342 * object to the <em>Error</em> state. </p></td></tr> 343 * <tr><td>setAudioStreamType </p></td> 344 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused, 345 * PlaybackCompleted}</p></td> 346 * <td>{Error}</p></td> 347 * <td>Successful invoke of this method does not change the state. In order for the 348 * target audio stream type to become effective, this method must be called before 349 * prepare() or prepareAsync().</p></td></tr> 350 * <tr><td>setDataSource </p></td> 351 * <td>{Idle} </p></td> 352 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, 353 * Error} </p></td> 354 * <td>Successful invoke of this method in a valid state transfers the 355 * object to the <em>Initialized</em> state. Calling this method in an 356 * invalid state throws an IllegalStateException.</p></td></tr> 357 * <tr><td>setDisplay </p></td> 358 * <td>any </p></td> 359 * <td>{} </p></td> 360 * <td>This method can be called in any state and calling it does not change 361 * the object state. </p></td></tr> 362 * <tr><td>setLooping </p></td> 363 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused, 364 * PlaybackCompleted}</p></td> 365 * <td>{Error}</p></td> 366 * <td>Successful invoke of this method in a valid state does not change 367 * the state. Calling this method in an 368 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr> 369 * <tr><td>isLooping </p></td> 370 * <td>any </p></td> 371 * <td>{} </p></td> 372 * <td>This method can be called in any state and calling it does not change 373 * the object state. </p></td></tr> 374 * <tr><td>setOnBufferingUpdateListener </p></td> 375 * <td>any </p></td> 376 * <td>{} </p></td> 377 * <td>This method can be called in any state and calling it does not change 378 * the object state. </p></td></tr> 379 * <tr><td>setOnCompletionListener </p></td> 380 * <td>any </p></td> 381 * <td>{} </p></td> 382 * <td>This method can be called in any state and calling it does not change 383 * the object state. </p></td></tr> 384 * <tr><td>setOnErrorListener </p></td> 385 * <td>any </p></td> 386 * <td>{} </p></td> 387 * <td>This method can be called in any state and calling it does not change 388 * the object state. </p></td></tr> 389 * <tr><td>setOnPreparedListener </p></td> 390 * <td>any </p></td> 391 * <td>{} </p></td> 392 * <td>This method can be called in any state and calling it does not change 393 * the object state. </p></td></tr> 394 * <tr><td>setOnSeekCompleteListener </p></td> 395 * <td>any </p></td> 396 * <td>{} </p></td> 397 * <td>This method can be called in any state and calling it does not change 398 * the object state. </p></td></tr> 399 * <tr><td>setScreenOnWhilePlaying</></td> 400 * <td>any </p></td> 401 * <td>{} </p></td> 402 * <td>This method can be called in any state and calling it does not change 403 * the object state. </p></td></tr> 404 * <tr><td>setVolume </p></td> 405 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused, 406 * PlaybackCompleted}</p></td> 407 * <td>{Error}</p></td> 408 * <td>Successful invoke of this method does not change the state. 409 * <tr><td>setWakeMode </p></td> 410 * <td>any </p></td> 411 * <td>{} </p></td> 412 * <td>This method can be called in any state and calling it does not change 413 * the object state.</p></td></tr> 414 * <tr><td>start </p></td> 415 * <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td> 416 * <td>{Idle, Initialized, Stopped, Error}</p></td> 417 * <td>Successful invoke of this method in a valid state transfers the 418 * object to the <em>Started</em> state. Calling this method in an 419 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr> 420 * <tr><td>stop </p></td> 421 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td> 422 * <td>{Idle, Initialized, Error}</p></td> 423 * <td>Successful invoke of this method in a valid state transfers the 424 * object to the <em>Stopped</em> state. Calling this method in an 425 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr> 426 * <tr><td>setAudioSessionId </p></td> 427 * <td>{Idle} </p></td> 428 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, 429 * Error} </p></td> 430 * <td>This method must be called in idle state as the audio session ID must be known before 431 * calling setDataSource. Calling it does not change the object state. </p></td></tr> 432 * <tr><td>getAudioSessionId </p></td> 433 * <td>any </p></td> 434 * <td>{} </p></td> 435 * <td>This method can be called in any state and calling it does not change 436 * the object state. </p></td></tr> 437 * 438 * </table> 439 * 440 * <a name="Permissions"></a> 441 * <h3>Permissions</h3> 442 * <p>One may need to declare a corresponding WAKE_LOCK permission {@link 443 * android.R.styleable#AndroidManifestUsesPermission <uses-permission>} 444 * element. 445 * 446 */ 447public class MediaPlayer 448{ 449 /** 450 Constant to retrieve only the new metadata since the last 451 call. 452 // FIXME: unhide. 453 // FIXME: add link to getMetadata(boolean, boolean) 454 {@hide} 455 */ 456 public static final boolean METADATA_UPDATE_ONLY = true; 457 458 /** 459 Constant to retrieve all the metadata. 460 // FIXME: unhide. 461 // FIXME: add link to getMetadata(boolean, boolean) 462 {@hide} 463 */ 464 public static final boolean METADATA_ALL = false; 465 466 /** 467 Constant to enable the metadata filter during retrieval. 468 // FIXME: unhide. 469 // FIXME: add link to getMetadata(boolean, boolean) 470 {@hide} 471 */ 472 public static final boolean APPLY_METADATA_FILTER = true; 473 474 /** 475 Constant to disable the metadata filter during retrieval. 476 // FIXME: unhide. 477 // FIXME: add link to getMetadata(boolean, boolean) 478 {@hide} 479 */ 480 public static final boolean BYPASS_METADATA_FILTER = false; 481 482 static { 483 System.loadLibrary("media_jni"); 484 native_init(); 485 } 486 487 private final static String TAG = "MediaPlayer"; 488 // Name of the remote interface for the media player. Must be kept 489 // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE 490 // macro invocation in IMediaPlayer.cpp 491 private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer"; 492 493 private int mNativeContext; // accessed by native methods 494 private int mListenerContext; // accessed by native methods 495 private Surface mSurface; // accessed by native methods 496 private SurfaceHolder mSurfaceHolder; 497 private EventHandler mEventHandler; 498 private PowerManager.WakeLock mWakeLock = null; 499 private boolean mScreenOnWhilePlaying; 500 private boolean mStayAwake; 501 502 /** 503 * Default constructor. Consider using one of the create() methods for 504 * synchronously instantiating a MediaPlayer from a Uri or resource. 505 * <p>When done with the MediaPlayer, you should call {@link #release()}, 506 * to free the resources. If not released, too many MediaPlayer instances may 507 * result in an exception.</p> 508 */ 509 public MediaPlayer() { 510 511 Looper looper; 512 if ((looper = Looper.myLooper()) != null) { 513 mEventHandler = new EventHandler(this, looper); 514 } else if ((looper = Looper.getMainLooper()) != null) { 515 mEventHandler = new EventHandler(this, looper); 516 } else { 517 mEventHandler = null; 518 } 519 520 /* Native setup requires a weak reference to our object. 521 * It's easier to create it here than in C++. 522 */ 523 native_setup(new WeakReference<MediaPlayer>(this)); 524 } 525 526 /* 527 * Update the MediaPlayer ISurface. Call after updating mSurface. 528 */ 529 private native void _setVideoSurface(); 530 531 /** 532 * Create a request parcel which can be routed to the native media 533 * player using {@link #invoke(Parcel, Parcel)}. The Parcel 534 * returned has the proper InterfaceToken set. The caller should 535 * not overwrite that token, i.e it can only append data to the 536 * Parcel. 537 * 538 * @return A parcel suitable to hold a request for the native 539 * player. 540 * {@hide} 541 */ 542 public Parcel newRequest() { 543 Parcel parcel = Parcel.obtain(); 544 parcel.writeInterfaceToken(IMEDIA_PLAYER); 545 return parcel; 546 } 547 548 /** 549 * Invoke a generic method on the native player using opaque 550 * parcels for the request and reply. Both payloads' format is a 551 * convention between the java caller and the native player. 552 * Must be called after setDataSource to make sure a native player 553 * exists. 554 * 555 * @param request Parcel with the data for the extension. The 556 * caller must use {@link #newRequest()} to get one. 557 * 558 * @param reply Output parcel with the data returned by the 559 * native player. 560 * 561 * @return The status code see utils/Errors.h 562 * {@hide} 563 */ 564 public int invoke(Parcel request, Parcel reply) { 565 int retcode = native_invoke(request, reply); 566 reply.setDataPosition(0); 567 return retcode; 568 } 569 570 /** 571 * Sets the SurfaceHolder to use for displaying the video portion of the media. 572 * This call is optional. Not calling it when playing back a video will 573 * result in only the audio track being played. 574 * 575 * @param sh the SurfaceHolder to use for video display 576 */ 577 public void setDisplay(SurfaceHolder sh) { 578 mSurfaceHolder = sh; 579 if (sh != null) { 580 mSurface = sh.getSurface(); 581 } else { 582 mSurface = null; 583 } 584 _setVideoSurface(); 585 updateSurfaceScreenOn(); 586 } 587 588 /** 589 * Convenience method to create a MediaPlayer for a given Uri. 590 * On success, {@link #prepare()} will already have been called and must not be called again. 591 * <p>When done with the MediaPlayer, you should call {@link #release()}, 592 * to free the resources. If not released, too many MediaPlayer instances will 593 * result in an exception.</p> 594 * 595 * @param context the Context to use 596 * @param uri the Uri from which to get the datasource 597 * @return a MediaPlayer object, or null if creation failed 598 */ 599 public static MediaPlayer create(Context context, Uri uri) { 600 return create (context, uri, null); 601 } 602 603 /** 604 * Convenience method to create a MediaPlayer for a given Uri. 605 * On success, {@link #prepare()} will already have been called and must not be called again. 606 * <p>When done with the MediaPlayer, you should call {@link #release()}, 607 * to free the resources. If not released, too many MediaPlayer instances will 608 * result in an exception.</p> 609 * 610 * @param context the Context to use 611 * @param uri the Uri from which to get the datasource 612 * @param holder the SurfaceHolder to use for displaying the video 613 * @return a MediaPlayer object, or null if creation failed 614 */ 615 public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) { 616 617 try { 618 MediaPlayer mp = new MediaPlayer(); 619 mp.setDataSource(context, uri); 620 if (holder != null) { 621 mp.setDisplay(holder); 622 } 623 mp.prepare(); 624 return mp; 625 } catch (IOException ex) { 626 Log.d(TAG, "create failed:", ex); 627 // fall through 628 } catch (IllegalArgumentException ex) { 629 Log.d(TAG, "create failed:", ex); 630 // fall through 631 } catch (SecurityException ex) { 632 Log.d(TAG, "create failed:", ex); 633 // fall through 634 } 635 636 return null; 637 } 638 639 /** 640 * Convenience method to create a MediaPlayer for a given resource id. 641 * On success, {@link #prepare()} will already have been called and must not be called again. 642 * <p>When done with the MediaPlayer, you should call {@link #release()}, 643 * to free the resources. If not released, too many MediaPlayer instances will 644 * result in an exception.</p> 645 * 646 * @param context the Context to use 647 * @param resid the raw resource id (<var>R.raw.<something></var>) for 648 * the resource to use as the datasource 649 * @return a MediaPlayer object, or null if creation failed 650 */ 651 public static MediaPlayer create(Context context, int resid) { 652 try { 653 AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid); 654 if (afd == null) return null; 655 656 MediaPlayer mp = new MediaPlayer(); 657 mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); 658 afd.close(); 659 mp.prepare(); 660 return mp; 661 } catch (IOException ex) { 662 Log.d(TAG, "create failed:", ex); 663 // fall through 664 } catch (IllegalArgumentException ex) { 665 Log.d(TAG, "create failed:", ex); 666 // fall through 667 } catch (SecurityException ex) { 668 Log.d(TAG, "create failed:", ex); 669 // fall through 670 } 671 return null; 672 } 673 674 /** 675 * Sets the data source as a content Uri. 676 * 677 * @param context the Context to use when resolving the Uri 678 * @param uri the Content URI of the data you want to play 679 * @throws IllegalStateException if it is called in an invalid state 680 */ 681 public void setDataSource(Context context, Uri uri) 682 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException { 683 setDataSource(context, uri, null); 684 } 685 686 /** 687 * Sets the data source as a content Uri. 688 * 689 * @param context the Context to use when resolving the Uri 690 * @param uri the Content URI of the data you want to play 691 * @param headers the headers to be sent together with the request for the data 692 * @throws IllegalStateException if it is called in an invalid state 693 * @hide pending API council 694 */ 695 public void setDataSource(Context context, Uri uri, Map<String, String> headers) 696 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException { 697 698 String scheme = uri.getScheme(); 699 if(scheme == null || scheme.equals("file")) { 700 setDataSource(uri.getPath()); 701 return; 702 } 703 704 AssetFileDescriptor fd = null; 705 try { 706 ContentResolver resolver = context.getContentResolver(); 707 fd = resolver.openAssetFileDescriptor(uri, "r"); 708 if (fd == null) { 709 return; 710 } 711 // Note: using getDeclaredLength so that our behavior is the same 712 // as previous versions when the content provider is returning 713 // a full file. 714 if (fd.getDeclaredLength() < 0) { 715 setDataSource(fd.getFileDescriptor()); 716 } else { 717 setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength()); 718 } 719 return; 720 } catch (SecurityException ex) { 721 } catch (IOException ex) { 722 } finally { 723 if (fd != null) { 724 fd.close(); 725 } 726 } 727 Log.d(TAG, "Couldn't open file on client side, trying server side"); 728 setDataSource(uri.toString(), headers); 729 return; 730 } 731 732 /** 733 * Sets the data source (file-path or http/rtsp URL) to use. 734 * 735 * @param path the path of the file, or the http/rtsp URL of the stream you want to play 736 * @throws IllegalStateException if it is called in an invalid state 737 */ 738 public native void setDataSource(String path) throws IOException, IllegalArgumentException, IllegalStateException; 739 740 /** 741 * Sets the data source (file-path or http/rtsp URL) to use. 742 * 743 * @param path the path of the file, or the http/rtsp URL of the stream you want to play 744 * @param headers the headers associated with the http request for the stream you want to play 745 * @throws IllegalStateException if it is called in an invalid state 746 * @hide pending API council 747 */ 748 public native void setDataSource(String path, Map<String, String> headers) 749 throws IOException, IllegalArgumentException, IllegalStateException; 750 751 /** 752 * Sets the data source (FileDescriptor) to use. It is the caller's responsibility 753 * to close the file descriptor. It is safe to do so as soon as this call returns. 754 * 755 * @param fd the FileDescriptor for the file you want to play 756 * @throws IllegalStateException if it is called in an invalid state 757 */ 758 public void setDataSource(FileDescriptor fd) 759 throws IOException, IllegalArgumentException, IllegalStateException { 760 // intentionally less than LONG_MAX 761 setDataSource(fd, 0, 0x7ffffffffffffffL); 762 } 763 764 /** 765 * Sets the data source (FileDescriptor) to use. The FileDescriptor must be 766 * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility 767 * to close the file descriptor. It is safe to do so as soon as this call returns. 768 * 769 * @param fd the FileDescriptor for the file you want to play 770 * @param offset the offset into the file where the data to be played starts, in bytes 771 * @param length the length in bytes of the data to be played 772 * @throws IllegalStateException if it is called in an invalid state 773 */ 774 public native void setDataSource(FileDescriptor fd, long offset, long length) 775 throws IOException, IllegalArgumentException, IllegalStateException; 776 777 /** 778 * Prepares the player for playback, synchronously. 779 * 780 * After setting the datasource and the display surface, you need to either 781 * call prepare() or prepareAsync(). For files, it is OK to call prepare(), 782 * which blocks until MediaPlayer is ready for playback. 783 * 784 * @throws IllegalStateException if it is called in an invalid state 785 */ 786 public native void prepare() throws IOException, IllegalStateException; 787 788 /** 789 * Prepares the player for playback, asynchronously. 790 * 791 * After setting the datasource and the display surface, you need to either 792 * call prepare() or prepareAsync(). For streams, you should call prepareAsync(), 793 * which returns immediately, rather than blocking until enough data has been 794 * buffered. 795 * 796 * @throws IllegalStateException if it is called in an invalid state 797 */ 798 public native void prepareAsync() throws IllegalStateException; 799 800 /** 801 * Starts or resumes playback. If playback had previously been paused, 802 * playback will continue from where it was paused. If playback had 803 * been stopped, or never started before, playback will start at the 804 * beginning. 805 * 806 * @throws IllegalStateException if it is called in an invalid state 807 */ 808 public void start() throws IllegalStateException { 809 stayAwake(true); 810 _start(); 811 } 812 813 private native void _start() throws IllegalStateException; 814 815 /** 816 * Stops playback after playback has been stopped or paused. 817 * 818 * @throws IllegalStateException if the internal player engine has not been 819 * initialized. 820 */ 821 public void stop() throws IllegalStateException { 822 stayAwake(false); 823 _stop(); 824 } 825 826 private native void _stop() throws IllegalStateException; 827 828 /** 829 * Pauses playback. Call start() to resume. 830 * 831 * @throws IllegalStateException if the internal player engine has not been 832 * initialized. 833 */ 834 public void pause() throws IllegalStateException { 835 stayAwake(false); 836 _pause(); 837 } 838 839 private native void _pause() throws IllegalStateException; 840 841 /** 842 * Set the low-level power management behavior for this MediaPlayer. This 843 * can be used when the MediaPlayer is not playing through a SurfaceHolder 844 * set with {@link #setDisplay(SurfaceHolder)} and thus can use the 845 * high-level {@link #setScreenOnWhilePlaying(boolean)} feature. 846 * 847 * <p>This function has the MediaPlayer access the low-level power manager 848 * service to control the device's power usage while playing is occurring. 849 * The parameter is a combination of {@link android.os.PowerManager} wake flags. 850 * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK} 851 * permission. 852 * By default, no attempt is made to keep the device awake during playback. 853 * 854 * @param context the Context to use 855 * @param mode the power/wake mode to set 856 * @see android.os.PowerManager 857 */ 858 public void setWakeMode(Context context, int mode) { 859 boolean washeld = false; 860 if (mWakeLock != null) { 861 if (mWakeLock.isHeld()) { 862 washeld = true; 863 mWakeLock.release(); 864 } 865 mWakeLock = null; 866 } 867 868 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 869 mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName()); 870 mWakeLock.setReferenceCounted(false); 871 if (washeld) { 872 mWakeLock.acquire(); 873 } 874 } 875 876 /** 877 * Control whether we should use the attached SurfaceHolder to keep the 878 * screen on while video playback is occurring. This is the preferred 879 * method over {@link #setWakeMode} where possible, since it doesn't 880 * require that the application have permission for low-level wake lock 881 * access. 882 * 883 * @param screenOn Supply true to keep the screen on, false to allow it 884 * to turn off. 885 */ 886 public void setScreenOnWhilePlaying(boolean screenOn) { 887 if (mScreenOnWhilePlaying != screenOn) { 888 mScreenOnWhilePlaying = screenOn; 889 updateSurfaceScreenOn(); 890 } 891 } 892 893 private void stayAwake(boolean awake) { 894 if (mWakeLock != null) { 895 if (awake && !mWakeLock.isHeld()) { 896 mWakeLock.acquire(); 897 } else if (!awake && mWakeLock.isHeld()) { 898 mWakeLock.release(); 899 } 900 } 901 mStayAwake = awake; 902 updateSurfaceScreenOn(); 903 } 904 905 private void updateSurfaceScreenOn() { 906 if (mSurfaceHolder != null) { 907 mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake); 908 } 909 } 910 911 /** 912 * Returns the width of the video. 913 * 914 * @return the width of the video, or 0 if there is no video, 915 * no display surface was set, or the width has not been determined 916 * yet. The OnVideoSizeChangedListener can be registered via 917 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)} 918 * to provide a notification when the width is available. 919 */ 920 public native int getVideoWidth(); 921 922 /** 923 * Returns the height of the video. 924 * 925 * @return the height of the video, or 0 if there is no video, 926 * no display surface was set, or the height has not been determined 927 * yet. The OnVideoSizeChangedListener can be registered via 928 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)} 929 * to provide a notification when the height is available. 930 */ 931 public native int getVideoHeight(); 932 933 /** 934 * Checks whether the MediaPlayer is playing. 935 * 936 * @return true if currently playing, false otherwise 937 */ 938 public native boolean isPlaying(); 939 940 /** 941 * Seeks to specified time position. 942 * 943 * @param msec the offset in milliseconds from the start to seek to 944 * @throws IllegalStateException if the internal player engine has not been 945 * initialized 946 */ 947 public native void seekTo(int msec) throws IllegalStateException; 948 949 /** 950 * Gets the current playback position. 951 * 952 * @return the current position in milliseconds 953 */ 954 public native int getCurrentPosition(); 955 956 /** 957 * Gets the duration of the file. 958 * 959 * @return the duration in milliseconds 960 */ 961 public native int getDuration(); 962 963 /** 964 * Gets the media metadata. 965 * 966 * @param update_only controls whether the full set of available 967 * metadata is returned or just the set that changed since the 968 * last call. See {@see #METADATA_UPDATE_ONLY} and {@see 969 * #METADATA_ALL}. 970 * 971 * @param apply_filter if true only metadata that matches the 972 * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see 973 * #BYPASS_METADATA_FILTER}. 974 * 975 * @return The metadata, possibly empty. null if an error occured. 976 // FIXME: unhide. 977 * {@hide} 978 */ 979 public Metadata getMetadata(final boolean update_only, 980 final boolean apply_filter) { 981 Parcel reply = Parcel.obtain(); 982 Metadata data = new Metadata(); 983 984 if (!native_getMetadata(update_only, apply_filter, reply)) { 985 reply.recycle(); 986 return null; 987 } 988 989 // Metadata takes over the parcel, don't recycle it unless 990 // there is an error. 991 if (!data.parse(reply)) { 992 reply.recycle(); 993 return null; 994 } 995 return data; 996 } 997 998 /** 999 * Set a filter for the metadata update notification and update 1000 * retrieval. The caller provides 2 set of metadata keys, allowed 1001 * and blocked. The blocked set always takes precedence over the 1002 * allowed one. 1003 * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as 1004 * shorthands to allow/block all or no metadata. 1005 * 1006 * By default, there is no filter set. 1007 * 1008 * @param allow Is the set of metadata the client is interested 1009 * in receiving new notifications for. 1010 * @param block Is the set of metadata the client is not interested 1011 * in receiving new notifications for. 1012 * @return The call status code. 1013 * 1014 // FIXME: unhide. 1015 * {@hide} 1016 */ 1017 public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) { 1018 // Do our serialization manually instead of calling 1019 // Parcel.writeArray since the sets are made of the same type 1020 // we avoid paying the price of calling writeValue (used by 1021 // writeArray) which burns an extra int per element to encode 1022 // the type. 1023 Parcel request = newRequest(); 1024 1025 // The parcel starts already with an interface token. There 1026 // are 2 filters. Each one starts with a 4bytes number to 1027 // store the len followed by a number of int (4 bytes as well) 1028 // representing the metadata type. 1029 int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size()); 1030 1031 if (request.dataCapacity() < capacity) { 1032 request.setDataCapacity(capacity); 1033 } 1034 1035 request.writeInt(allow.size()); 1036 for(Integer t: allow) { 1037 request.writeInt(t); 1038 } 1039 request.writeInt(block.size()); 1040 for(Integer t: block) { 1041 request.writeInt(t); 1042 } 1043 return native_setMetadataFilter(request); 1044 } 1045 1046 /** 1047 * Releases resources associated with this MediaPlayer object. 1048 * It is considered good practice to call this method when you're 1049 * done using the MediaPlayer. 1050 */ 1051 public void release() { 1052 stayAwake(false); 1053 updateSurfaceScreenOn(); 1054 mOnPreparedListener = null; 1055 mOnBufferingUpdateListener = null; 1056 mOnCompletionListener = null; 1057 mOnSeekCompleteListener = null; 1058 mOnErrorListener = null; 1059 mOnInfoListener = null; 1060 mOnVideoSizeChangedListener = null; 1061 _release(); 1062 } 1063 1064 private native void _release(); 1065 1066 /** 1067 * Resets the MediaPlayer to its uninitialized state. After calling 1068 * this method, you will have to initialize it again by setting the 1069 * data source and calling prepare(). 1070 */ 1071 public void reset() { 1072 stayAwake(false); 1073 _reset(); 1074 // make sure none of the listeners get called anymore 1075 mEventHandler.removeCallbacksAndMessages(null); 1076 } 1077 1078 private native void _reset(); 1079 1080 /** 1081 * Suspends the MediaPlayer. The only methods that may be called while 1082 * suspended are {@link #reset()}, {@link #release()} and {@link #resume()}. 1083 * MediaPlayer will release its hardware resources as far as 1084 * possible and reasonable. A successfully suspended MediaPlayer will 1085 * cease sending events. 1086 * If suspension is successful, this method returns true, otherwise 1087 * false is returned and the player's state is not affected. 1088 * @hide 1089 */ 1090 public boolean suspend() { 1091 if (native_suspend_resume(true) < 0) { 1092 return false; 1093 } 1094 1095 stayAwake(false); 1096 1097 // make sure none of the listeners get called anymore 1098 mEventHandler.removeCallbacksAndMessages(null); 1099 1100 return true; 1101 } 1102 1103 /** 1104 * Resumes the MediaPlayer. Only to be called after a previous (successful) 1105 * call to {@link #suspend()}. 1106 * MediaPlayer will return to a state close to what it was in before 1107 * suspension. 1108 * @hide 1109 */ 1110 public boolean resume() { 1111 if (native_suspend_resume(false) < 0) { 1112 return false; 1113 } 1114 1115 if (isPlaying()) { 1116 stayAwake(true); 1117 } 1118 1119 return true; 1120 } 1121 1122 /** 1123 * @hide 1124 */ 1125 private native int native_suspend_resume(boolean isSuspend); 1126 1127 /** 1128 * Sets the audio stream type for this MediaPlayer. See {@link AudioManager} 1129 * for a list of stream types. Must call this method before prepare() or 1130 * prepareAsync() in order for the target stream type to become effective 1131 * thereafter. 1132 * 1133 * @param streamtype the audio stream type 1134 * @see android.media.AudioManager 1135 */ 1136 public native void setAudioStreamType(int streamtype); 1137 1138 /** 1139 * Sets the player to be looping or non-looping. 1140 * 1141 * @param looping whether to loop or not 1142 */ 1143 public native void setLooping(boolean looping); 1144 1145 /** 1146 * Checks whether the MediaPlayer is looping or non-looping. 1147 * 1148 * @return true if the MediaPlayer is currently looping, false otherwise 1149 */ 1150 public native boolean isLooping(); 1151 1152 /** 1153 * Sets the volume on this player. 1154 * This API is recommended for balancing the output of audio streams 1155 * within an application. Unless you are writing an application to 1156 * control user settings, this API should be used in preference to 1157 * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of 1158 * a particular type. Note that the passed volume values are raw scalars. 1159 * UI controls should be scaled logarithmically. 1160 * 1161 * @param leftVolume left volume scalar 1162 * @param rightVolume right volume scalar 1163 */ 1164 public native void setVolume(float leftVolume, float rightVolume); 1165 1166 /** 1167 * Currently not implemented, returns null. 1168 * @deprecated 1169 * @hide 1170 */ 1171 public native Bitmap getFrameAt(int msec) throws IllegalStateException; 1172 1173 /** 1174 * Sets the audio session ID. 1175 * 1176 * @param sessionId: the audio session ID. 1177 * The audio session ID is a system wide unique identifier for the audio stream played by 1178 * this MediaPlayer instance. 1179 * The primary use of the audio session ID is to associate audio effects to a particular 1180 * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect, 1181 * this effect will be applied only to the audio content of media players within the same 1182 * audio session and not to the output mix. 1183 * When created, a MediaPlayer instance automatically generates its own audio session ID. 1184 * However, it is possible to force this player to be part of an already existing audio session 1185 * by calling this method. 1186 * This method must be called before one of the overloaded <code> setDataSource </code> methods. 1187 * @throws IllegalStateException if it is called in an invalid state 1188 * 1189 // FIXME: unhide. 1190 // FIXME: link to AudioEffect class when public. 1191 * @hide 1192 */ 1193 public native void setAudioSessionId(int sessionId) throws IllegalArgumentException, IllegalStateException; 1194 1195 /** 1196 * Returns the audio session ID. 1197 * 1198 * @return the audio session ID. {@see #setAudioSessionId(int)}. 1199 * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed. 1200 // FIXME: unhide. 1201 * @hide 1202 */ 1203 public native int getAudioSessionId(); 1204 1205 /** 1206 * @param request Parcel destinated to the media player. The 1207 * Interface token must be set to the IMediaPlayer 1208 * one to be routed correctly through the system. 1209 * @param reply[out] Parcel that will contain the reply. 1210 * @return The status code. 1211 */ 1212 private native final int native_invoke(Parcel request, Parcel reply); 1213 1214 1215 /** 1216 * @param update_only If true fetch only the set of metadata that have 1217 * changed since the last invocation of getMetadata. 1218 * The set is built using the unfiltered 1219 * notifications the native player sent to the 1220 * MediaPlayerService during that period of 1221 * time. If false, all the metadatas are considered. 1222 * @param apply_filter If true, once the metadata set has been built based on 1223 * the value update_only, the current filter is applied. 1224 * @param reply[out] On return contains the serialized 1225 * metadata. Valid only if the call was successful. 1226 * @return The status code. 1227 */ 1228 private native final boolean native_getMetadata(boolean update_only, 1229 boolean apply_filter, 1230 Parcel reply); 1231 1232 /** 1233 * @param request Parcel with the 2 serialized lists of allowed 1234 * metadata types followed by the one to be 1235 * dropped. Each list starts with an integer 1236 * indicating the number of metadata type elements. 1237 * @return The status code. 1238 */ 1239 private native final int native_setMetadataFilter(Parcel request); 1240 1241 private static native final void native_init(); 1242 private native final void native_setup(Object mediaplayer_this); 1243 private native final void native_finalize(); 1244 1245 @Override 1246 protected void finalize() { native_finalize(); } 1247 1248 /* Do not change these values without updating their counterparts 1249 * in include/media/mediaplayer.h! 1250 */ 1251 private static final int MEDIA_NOP = 0; // interface test message 1252 private static final int MEDIA_PREPARED = 1; 1253 private static final int MEDIA_PLAYBACK_COMPLETE = 2; 1254 private static final int MEDIA_BUFFERING_UPDATE = 3; 1255 private static final int MEDIA_SEEK_COMPLETE = 4; 1256 private static final int MEDIA_SET_VIDEO_SIZE = 5; 1257 private static final int MEDIA_ERROR = 100; 1258 private static final int MEDIA_INFO = 200; 1259 1260 private class EventHandler extends Handler 1261 { 1262 private MediaPlayer mMediaPlayer; 1263 1264 public EventHandler(MediaPlayer mp, Looper looper) { 1265 super(looper); 1266 mMediaPlayer = mp; 1267 } 1268 1269 @Override 1270 public void handleMessage(Message msg) { 1271 if (mMediaPlayer.mNativeContext == 0) { 1272 Log.w(TAG, "mediaplayer went away with unhandled events"); 1273 return; 1274 } 1275 switch(msg.what) { 1276 case MEDIA_PREPARED: 1277 if (mOnPreparedListener != null) 1278 mOnPreparedListener.onPrepared(mMediaPlayer); 1279 return; 1280 1281 case MEDIA_PLAYBACK_COMPLETE: 1282 if (mOnCompletionListener != null) 1283 mOnCompletionListener.onCompletion(mMediaPlayer); 1284 stayAwake(false); 1285 return; 1286 1287 case MEDIA_BUFFERING_UPDATE: 1288 if (mOnBufferingUpdateListener != null) 1289 mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1); 1290 return; 1291 1292 case MEDIA_SEEK_COMPLETE: 1293 if (mOnSeekCompleteListener != null) 1294 mOnSeekCompleteListener.onSeekComplete(mMediaPlayer); 1295 return; 1296 1297 case MEDIA_SET_VIDEO_SIZE: 1298 if (mOnVideoSizeChangedListener != null) 1299 mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2); 1300 return; 1301 1302 case MEDIA_ERROR: 1303 // For PV specific error values (msg.arg2) look in 1304 // opencore/pvmi/pvmf/include/pvmf_return_codes.h 1305 Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")"); 1306 boolean error_was_handled = false; 1307 if (mOnErrorListener != null) { 1308 error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2); 1309 } 1310 if (mOnCompletionListener != null && ! error_was_handled) { 1311 mOnCompletionListener.onCompletion(mMediaPlayer); 1312 } 1313 stayAwake(false); 1314 return; 1315 1316 case MEDIA_INFO: 1317 // For PV specific code values (msg.arg2) look in 1318 // opencore/pvmi/pvmf/include/pvmf_return_codes.h 1319 Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")"); 1320 if (mOnInfoListener != null) { 1321 mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2); 1322 } 1323 // No real default action so far. 1324 return; 1325 1326 case MEDIA_NOP: // interface test message - ignore 1327 break; 1328 1329 default: 1330 Log.e(TAG, "Unknown message type " + msg.what); 1331 return; 1332 } 1333 } 1334 } 1335 1336 /** 1337 * Called from native code when an interesting event happens. This method 1338 * just uses the EventHandler system to post the event back to the main app thread. 1339 * We use a weak reference to the original MediaPlayer object so that the native 1340 * code is safe from the object disappearing from underneath it. (This is 1341 * the cookie passed to native_setup().) 1342 */ 1343 private static void postEventFromNative(Object mediaplayer_ref, 1344 int what, int arg1, int arg2, Object obj) 1345 { 1346 MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get(); 1347 if (mp == null) { 1348 return; 1349 } 1350 1351 if (mp.mEventHandler != null) { 1352 Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj); 1353 mp.mEventHandler.sendMessage(m); 1354 } 1355 } 1356 1357 /** 1358 * Interface definition for a callback to be invoked when the media 1359 * source is ready for playback. 1360 */ 1361 public interface OnPreparedListener 1362 { 1363 /** 1364 * Called when the media file is ready for playback. 1365 * 1366 * @param mp the MediaPlayer that is ready for playback 1367 */ 1368 void onPrepared(MediaPlayer mp); 1369 } 1370 1371 /** 1372 * Register a callback to be invoked when the media source is ready 1373 * for playback. 1374 * 1375 * @param listener the callback that will be run 1376 */ 1377 public void setOnPreparedListener(OnPreparedListener listener) 1378 { 1379 mOnPreparedListener = listener; 1380 } 1381 1382 private OnPreparedListener mOnPreparedListener; 1383 1384 /** 1385 * Interface definition for a callback to be invoked when playback of 1386 * a media source has completed. 1387 */ 1388 public interface OnCompletionListener 1389 { 1390 /** 1391 * Called when the end of a media source is reached during playback. 1392 * 1393 * @param mp the MediaPlayer that reached the end of the file 1394 */ 1395 void onCompletion(MediaPlayer mp); 1396 } 1397 1398 /** 1399 * Register a callback to be invoked when the end of a media source 1400 * has been reached during playback. 1401 * 1402 * @param listener the callback that will be run 1403 */ 1404 public void setOnCompletionListener(OnCompletionListener listener) 1405 { 1406 mOnCompletionListener = listener; 1407 } 1408 1409 private OnCompletionListener mOnCompletionListener; 1410 1411 /** 1412 * Interface definition of a callback to be invoked indicating buffering 1413 * status of a media resource being streamed over the network. 1414 */ 1415 public interface OnBufferingUpdateListener 1416 { 1417 /** 1418 * Called to update status in buffering a media stream. 1419 * 1420 * @param mp the MediaPlayer the update pertains to 1421 * @param percent the percentage (0-100) of the buffer 1422 * that has been filled thus far 1423 */ 1424 void onBufferingUpdate(MediaPlayer mp, int percent); 1425 } 1426 1427 /** 1428 * Register a callback to be invoked when the status of a network 1429 * stream's buffer has changed. 1430 * 1431 * @param listener the callback that will be run. 1432 */ 1433 public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener) 1434 { 1435 mOnBufferingUpdateListener = listener; 1436 } 1437 1438 private OnBufferingUpdateListener mOnBufferingUpdateListener; 1439 1440 /** 1441 * Interface definition of a callback to be invoked indicating 1442 * the completion of a seek operation. 1443 */ 1444 public interface OnSeekCompleteListener 1445 { 1446 /** 1447 * Called to indicate the completion of a seek operation. 1448 * 1449 * @param mp the MediaPlayer that issued the seek operation 1450 */ 1451 public void onSeekComplete(MediaPlayer mp); 1452 } 1453 1454 /** 1455 * Register a callback to be invoked when a seek operation has been 1456 * completed. 1457 * 1458 * @param listener the callback that will be run 1459 */ 1460 public void setOnSeekCompleteListener(OnSeekCompleteListener listener) 1461 { 1462 mOnSeekCompleteListener = listener; 1463 } 1464 1465 private OnSeekCompleteListener mOnSeekCompleteListener; 1466 1467 /** 1468 * Interface definition of a callback to be invoked when the 1469 * video size is first known or updated 1470 */ 1471 public interface OnVideoSizeChangedListener 1472 { 1473 /** 1474 * Called to indicate the video size 1475 * 1476 * @param mp the MediaPlayer associated with this callback 1477 * @param width the width of the video 1478 * @param height the height of the video 1479 */ 1480 public void onVideoSizeChanged(MediaPlayer mp, int width, int height); 1481 } 1482 1483 /** 1484 * Register a callback to be invoked when the video size is 1485 * known or updated. 1486 * 1487 * @param listener the callback that will be run 1488 */ 1489 public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener) 1490 { 1491 mOnVideoSizeChangedListener = listener; 1492 } 1493 1494 private OnVideoSizeChangedListener mOnVideoSizeChangedListener; 1495 1496 /* Do not change these values without updating their counterparts 1497 * in include/media/mediaplayer.h! 1498 */ 1499 /** Unspecified media player error. 1500 * @see android.media.MediaPlayer.OnErrorListener 1501 */ 1502 public static final int MEDIA_ERROR_UNKNOWN = 1; 1503 1504 /** Media server died. In this case, the application must release the 1505 * MediaPlayer object and instantiate a new one. 1506 * @see android.media.MediaPlayer.OnErrorListener 1507 */ 1508 public static final int MEDIA_ERROR_SERVER_DIED = 100; 1509 1510 /** The video is streamed and its container is not valid for progressive 1511 * playback i.e the video's index (e.g moov atom) is not at the start of the 1512 * file. 1513 * @see android.media.MediaPlayer.OnErrorListener 1514 */ 1515 public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200; 1516 1517 /** 1518 * Interface definition of a callback to be invoked when there 1519 * has been an error during an asynchronous operation (other errors 1520 * will throw exceptions at method call time). 1521 */ 1522 public interface OnErrorListener 1523 { 1524 /** 1525 * Called to indicate an error. 1526 * 1527 * @param mp the MediaPlayer the error pertains to 1528 * @param what the type of error that has occurred: 1529 * <ul> 1530 * <li>{@link #MEDIA_ERROR_UNKNOWN} 1531 * <li>{@link #MEDIA_ERROR_SERVER_DIED} 1532 * </ul> 1533 * @param extra an extra code, specific to the error. Typically 1534 * implementation dependant. 1535 * @return True if the method handled the error, false if it didn't. 1536 * Returning false, or not having an OnErrorListener at all, will 1537 * cause the OnCompletionListener to be called. 1538 */ 1539 boolean onError(MediaPlayer mp, int what, int extra); 1540 } 1541 1542 /** 1543 * Register a callback to be invoked when an error has happened 1544 * during an asynchronous operation. 1545 * 1546 * @param listener the callback that will be run 1547 */ 1548 public void setOnErrorListener(OnErrorListener listener) 1549 { 1550 mOnErrorListener = listener; 1551 } 1552 1553 private OnErrorListener mOnErrorListener; 1554 1555 1556 /* Do not change these values without updating their counterparts 1557 * in include/media/mediaplayer.h! 1558 */ 1559 /** Unspecified media player info. 1560 * @see android.media.MediaPlayer.OnInfoListener 1561 */ 1562 public static final int MEDIA_INFO_UNKNOWN = 1; 1563 1564 /** The video is too complex for the decoder: it can't decode frames fast 1565 * enough. Possibly only the audio plays fine at this stage. 1566 * @see android.media.MediaPlayer.OnInfoListener 1567 */ 1568 public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; 1569 1570 /** MediaPlayer is temporarily pausing playback internally in order to 1571 * buffer more data. 1572 */ 1573 public static final int MEDIA_INFO_BUFFERING_START = 701; 1574 1575 /** MediaPlayer is resuming playback after filling buffers. 1576 */ 1577 public static final int MEDIA_INFO_BUFFERING_END = 702; 1578 1579 /** Bad interleaving means that a media has been improperly interleaved or 1580 * not interleaved at all, e.g has all the video samples first then all the 1581 * audio ones. Video is playing but a lot of disk seeks may be happening. 1582 * @see android.media.MediaPlayer.OnInfoListener 1583 */ 1584 public static final int MEDIA_INFO_BAD_INTERLEAVING = 800; 1585 1586 /** The media cannot be seeked (e.g live stream) 1587 * @see android.media.MediaPlayer.OnInfoListener 1588 */ 1589 public static final int MEDIA_INFO_NOT_SEEKABLE = 801; 1590 1591 /** A new set of metadata is available. 1592 * @see android.media.MediaPlayer.OnInfoListener 1593 */ 1594 public static final int MEDIA_INFO_METADATA_UPDATE = 802; 1595 1596 /** 1597 * Interface definition of a callback to be invoked to communicate some 1598 * info and/or warning about the media or its playback. 1599 */ 1600 public interface OnInfoListener 1601 { 1602 /** 1603 * Called to indicate an info or a warning. 1604 * 1605 * @param mp the MediaPlayer the info pertains to. 1606 * @param what the type of info or warning. 1607 * <ul> 1608 * <li>{@link #MEDIA_INFO_UNKNOWN} 1609 * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING} 1610 * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING} 1611 * <li>{@link #MEDIA_INFO_NOT_SEEKABLE} 1612 * <li>{@link #MEDIA_INFO_METADATA_UPDATE} 1613 * </ul> 1614 * @param extra an extra code, specific to the info. Typically 1615 * implementation dependant. 1616 * @return True if the method handled the info, false if it didn't. 1617 * Returning false, or not having an OnErrorListener at all, will 1618 * cause the info to be discarded. 1619 */ 1620 boolean onInfo(MediaPlayer mp, int what, int extra); 1621 } 1622 1623 /** 1624 * Register a callback to be invoked when an info/warning is available. 1625 * 1626 * @param listener the callback that will be run 1627 */ 1628 public void setOnInfoListener(OnInfoListener listener) 1629 { 1630 mOnInfoListener = listener; 1631 } 1632 1633 private OnInfoListener mOnInfoListener; 1634 1635 /** 1636 * @hide 1637 */ 1638 public native static int snoop(short [] outData, int kind); 1639} 1640