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