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