MediaPlayer.java revision d01ec6eab019e46398975202e9e4a198a603ad99
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 */ 749 public void setDataSource(Context context, Uri uri, Map<String, String> headers) 750 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException { 751 752 String scheme = uri.getScheme(); 753 if(scheme == null || scheme.equals("file")) { 754 setDataSource(uri.getPath()); 755 return; 756 } 757 758 AssetFileDescriptor fd = null; 759 try { 760 ContentResolver resolver = context.getContentResolver(); 761 fd = resolver.openAssetFileDescriptor(uri, "r"); 762 if (fd == null) { 763 return; 764 } 765 // Note: using getDeclaredLength so that our behavior is the same 766 // as previous versions when the content provider is returning 767 // a full file. 768 if (fd.getDeclaredLength() < 0) { 769 setDataSource(fd.getFileDescriptor()); 770 } else { 771 setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength()); 772 } 773 return; 774 } catch (SecurityException ex) { 775 } catch (IOException ex) { 776 } finally { 777 if (fd != null) { 778 fd.close(); 779 } 780 } 781 Log.d(TAG, "Couldn't open file on client side, trying server side"); 782 setDataSource(uri.toString(), headers); 783 return; 784 } 785 786 /** 787 * Sets the data source (file-path or http/rtsp URL) to use. 788 * 789 * @param path the path of the file, or the http/rtsp URL of the stream you want to play 790 * @throws IllegalStateException if it is called in an invalid state 791 */ 792 public native void setDataSource(String path) throws IOException, IllegalArgumentException, IllegalStateException; 793 794 /** 795 * Sets the data source (file-path or http/rtsp URL) to use. 796 * 797 * @param path the path of the file, or the http/rtsp URL of the stream you want to play 798 * @param headers the headers associated with the http request for the stream you want to play 799 * @throws IllegalStateException if it is called in an invalid state 800 * @hide pending API council 801 */ 802 public native void setDataSource(String path, Map<String, String> headers) 803 throws IOException, IllegalArgumentException, IllegalStateException; 804 805 /** 806 * Sets the data source (FileDescriptor) to use. It is the caller's responsibility 807 * to close the file descriptor. It is safe to do so as soon as this call returns. 808 * 809 * @param fd the FileDescriptor for the file you want to play 810 * @throws IllegalStateException if it is called in an invalid state 811 */ 812 public void setDataSource(FileDescriptor fd) 813 throws IOException, IllegalArgumentException, IllegalStateException { 814 // intentionally less than LONG_MAX 815 setDataSource(fd, 0, 0x7ffffffffffffffL); 816 } 817 818 /** 819 * Sets the data source (FileDescriptor) to use. The FileDescriptor must be 820 * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility 821 * to close the file descriptor. It is safe to do so as soon as this call returns. 822 * 823 * @param fd the FileDescriptor for the file you want to play 824 * @param offset the offset into the file where the data to be played starts, in bytes 825 * @param length the length in bytes of the data to be played 826 * @throws IllegalStateException if it is called in an invalid state 827 */ 828 public native void setDataSource(FileDescriptor fd, long offset, long length) 829 throws IOException, IllegalArgumentException, IllegalStateException; 830 831 /** 832 * Prepares the player for playback, synchronously. 833 * 834 * After setting the datasource and the display surface, you need to either 835 * call prepare() or prepareAsync(). For files, it is OK to call prepare(), 836 * which blocks until MediaPlayer is ready for playback. 837 * 838 * @throws IllegalStateException if it is called in an invalid state 839 */ 840 public native void prepare() throws IOException, IllegalStateException; 841 842 /** 843 * Prepares the player for playback, asynchronously. 844 * 845 * After setting the datasource and the display surface, you need to either 846 * call prepare() or prepareAsync(). For streams, you should call prepareAsync(), 847 * which returns immediately, rather than blocking until enough data has been 848 * buffered. 849 * 850 * @throws IllegalStateException if it is called in an invalid state 851 */ 852 public native void prepareAsync() throws IllegalStateException; 853 854 /** 855 * Starts or resumes playback. If playback had previously been paused, 856 * playback will continue from where it was paused. If playback had 857 * been stopped, or never started before, playback will start at the 858 * beginning. 859 * 860 * @throws IllegalStateException if it is called in an invalid state 861 */ 862 public void start() throws IllegalStateException { 863 stayAwake(true); 864 _start(); 865 } 866 867 private native void _start() throws IllegalStateException; 868 869 /** 870 * Stops playback after playback has been stopped or paused. 871 * 872 * @throws IllegalStateException if the internal player engine has not been 873 * initialized. 874 */ 875 public void stop() throws IllegalStateException { 876 stayAwake(false); 877 _stop(); 878 } 879 880 private native void _stop() throws IllegalStateException; 881 882 /** 883 * Pauses playback. Call start() to resume. 884 * 885 * @throws IllegalStateException if the internal player engine has not been 886 * initialized. 887 */ 888 public void pause() throws IllegalStateException { 889 stayAwake(false); 890 _pause(); 891 } 892 893 private native void _pause() throws IllegalStateException; 894 895 /** 896 * Set the low-level power management behavior for this MediaPlayer. This 897 * can be used when the MediaPlayer is not playing through a SurfaceHolder 898 * set with {@link #setDisplay(SurfaceHolder)} and thus can use the 899 * high-level {@link #setScreenOnWhilePlaying(boolean)} feature. 900 * 901 * <p>This function has the MediaPlayer access the low-level power manager 902 * service to control the device's power usage while playing is occurring. 903 * The parameter is a combination of {@link android.os.PowerManager} wake flags. 904 * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK} 905 * permission. 906 * By default, no attempt is made to keep the device awake during playback. 907 * 908 * @param context the Context to use 909 * @param mode the power/wake mode to set 910 * @see android.os.PowerManager 911 */ 912 public void setWakeMode(Context context, int mode) { 913 boolean washeld = false; 914 if (mWakeLock != null) { 915 if (mWakeLock.isHeld()) { 916 washeld = true; 917 mWakeLock.release(); 918 } 919 mWakeLock = null; 920 } 921 922 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 923 mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName()); 924 mWakeLock.setReferenceCounted(false); 925 if (washeld) { 926 mWakeLock.acquire(); 927 } 928 } 929 930 /** 931 * Control whether we should use the attached SurfaceHolder to keep the 932 * screen on while video playback is occurring. This is the preferred 933 * method over {@link #setWakeMode} where possible, since it doesn't 934 * require that the application have permission for low-level wake lock 935 * access. 936 * 937 * @param screenOn Supply true to keep the screen on, false to allow it 938 * to turn off. 939 */ 940 public void setScreenOnWhilePlaying(boolean screenOn) { 941 if (mScreenOnWhilePlaying != screenOn) { 942 mScreenOnWhilePlaying = screenOn; 943 updateSurfaceScreenOn(); 944 } 945 } 946 947 private void stayAwake(boolean awake) { 948 if (mWakeLock != null) { 949 if (awake && !mWakeLock.isHeld()) { 950 mWakeLock.acquire(); 951 } else if (!awake && mWakeLock.isHeld()) { 952 mWakeLock.release(); 953 } 954 } 955 mStayAwake = awake; 956 updateSurfaceScreenOn(); 957 } 958 959 private void updateSurfaceScreenOn() { 960 if (mSurfaceHolder != null) { 961 mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake); 962 } 963 } 964 965 /** 966 * Returns the width of the video. 967 * 968 * @return the width of the video, or 0 if there is no video, 969 * no display surface was set, or the width has not been determined 970 * yet. The OnVideoSizeChangedListener can be registered via 971 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)} 972 * to provide a notification when the width is available. 973 */ 974 public native int getVideoWidth(); 975 976 /** 977 * Returns the height of the video. 978 * 979 * @return the height of the video, or 0 if there is no video, 980 * no display surface was set, or the height has not been determined 981 * yet. The OnVideoSizeChangedListener can be registered via 982 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)} 983 * to provide a notification when the height is available. 984 */ 985 public native int getVideoHeight(); 986 987 /** 988 * Checks whether the MediaPlayer is playing. 989 * 990 * @return true if currently playing, false otherwise 991 */ 992 public native boolean isPlaying(); 993 994 /** 995 * Seeks to specified time position. 996 * 997 * @param msec the offset in milliseconds from the start to seek to 998 * @throws IllegalStateException if the internal player engine has not been 999 * initialized 1000 */ 1001 public native void seekTo(int msec) throws IllegalStateException; 1002 1003 /** 1004 * Gets the current playback position. 1005 * 1006 * @return the current position in milliseconds 1007 */ 1008 public native int getCurrentPosition(); 1009 1010 /** 1011 * Gets the duration of the file. 1012 * 1013 * @return the duration in milliseconds 1014 */ 1015 public native int getDuration(); 1016 1017 /** 1018 * Gets the media metadata. 1019 * 1020 * @param update_only controls whether the full set of available 1021 * metadata is returned or just the set that changed since the 1022 * last call. See {@see #METADATA_UPDATE_ONLY} and {@see 1023 * #METADATA_ALL}. 1024 * 1025 * @param apply_filter if true only metadata that matches the 1026 * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see 1027 * #BYPASS_METADATA_FILTER}. 1028 * 1029 * @return The metadata, possibly empty. null if an error occured. 1030 // FIXME: unhide. 1031 * {@hide} 1032 */ 1033 public Metadata getMetadata(final boolean update_only, 1034 final boolean apply_filter) { 1035 Parcel reply = Parcel.obtain(); 1036 Metadata data = new Metadata(); 1037 1038 if (!native_getMetadata(update_only, apply_filter, reply)) { 1039 reply.recycle(); 1040 return null; 1041 } 1042 1043 // Metadata takes over the parcel, don't recycle it unless 1044 // there is an error. 1045 if (!data.parse(reply)) { 1046 reply.recycle(); 1047 return null; 1048 } 1049 return data; 1050 } 1051 1052 /** 1053 * Set a filter for the metadata update notification and update 1054 * retrieval. The caller provides 2 set of metadata keys, allowed 1055 * and blocked. The blocked set always takes precedence over the 1056 * allowed one. 1057 * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as 1058 * shorthands to allow/block all or no metadata. 1059 * 1060 * By default, there is no filter set. 1061 * 1062 * @param allow Is the set of metadata the client is interested 1063 * in receiving new notifications for. 1064 * @param block Is the set of metadata the client is not interested 1065 * in receiving new notifications for. 1066 * @return The call status code. 1067 * 1068 // FIXME: unhide. 1069 * {@hide} 1070 */ 1071 public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) { 1072 // Do our serialization manually instead of calling 1073 // Parcel.writeArray since the sets are made of the same type 1074 // we avoid paying the price of calling writeValue (used by 1075 // writeArray) which burns an extra int per element to encode 1076 // the type. 1077 Parcel request = newRequest(); 1078 1079 // The parcel starts already with an interface token. There 1080 // are 2 filters. Each one starts with a 4bytes number to 1081 // store the len followed by a number of int (4 bytes as well) 1082 // representing the metadata type. 1083 int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size()); 1084 1085 if (request.dataCapacity() < capacity) { 1086 request.setDataCapacity(capacity); 1087 } 1088 1089 request.writeInt(allow.size()); 1090 for(Integer t: allow) { 1091 request.writeInt(t); 1092 } 1093 request.writeInt(block.size()); 1094 for(Integer t: block) { 1095 request.writeInt(t); 1096 } 1097 return native_setMetadataFilter(request); 1098 } 1099 1100 /** 1101 * Releases resources associated with this MediaPlayer object. 1102 * It is considered good practice to call this method when you're 1103 * done using the MediaPlayer. For instance, whenever the Activity 1104 * of an application is paused, this method should be invoked to 1105 * release the MediaPlayer object. In addition to unnecessary resources 1106 * (such as memory and instances of codecs) being hold, failure to 1107 * call this method immediately if a MediaPlayer object is no longer 1108 * needed may also lead to continuous battery consumption for mobile 1109 * devices, and playback failure if no multiple instances of the 1110 * same codec is supported on a device. 1111 */ 1112 public void release() { 1113 stayAwake(false); 1114 updateSurfaceScreenOn(); 1115 mOnPreparedListener = null; 1116 mOnBufferingUpdateListener = null; 1117 mOnCompletionListener = null; 1118 mOnSeekCompleteListener = null; 1119 mOnErrorListener = null; 1120 mOnInfoListener = null; 1121 mOnVideoSizeChangedListener = null; 1122 mOnTimedTextListener = 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 parameter indicated by key. 1232 * @param key key indicates the parameter to be set. 1233 * @param value value of the parameter to be set. 1234 * @return true if the parameter is set successfully, false otherwise 1235 * {@hide} 1236 */ 1237 public native boolean setParameter(int key, Parcel value); 1238 1239 /** 1240 * Sets the parameter indicated by key. 1241 * @param key key indicates the parameter to be set. 1242 * @param value value of the parameter to be set. 1243 * @return true if the parameter is set successfully, false otherwise 1244 * {@hide} 1245 */ 1246 public boolean setParameter(int key, String value) { 1247 Parcel p = Parcel.obtain(); 1248 p.writeString(value); 1249 return setParameter(key, p); 1250 } 1251 1252 /** 1253 * Sets the parameter indicated by key. 1254 * @param key key indicates the parameter to be set. 1255 * @param value value of the parameter to be set. 1256 * @return true if the parameter is set successfully, false otherwise 1257 * {@hide} 1258 */ 1259 public boolean setParameter(int key, int value) { 1260 Parcel p = Parcel.obtain(); 1261 p.writeInt(value); 1262 return setParameter(key, p); 1263 } 1264 1265 /** 1266 * Gets the value of the parameter indicated by key. 1267 * @param key key indicates the parameter to get. 1268 * @param reply value of the parameter to get. 1269 */ 1270 private native void getParameter(int key, Parcel reply); 1271 1272 /** 1273 * Gets the value of the parameter indicated by key. 1274 * @param key key indicates the parameter to get. 1275 * @return value of the parameter. 1276 * {@hide} 1277 */ 1278 public Parcel getParcelParameter(int key) { 1279 Parcel p = Parcel.obtain(); 1280 getParameter(key, p); 1281 return p; 1282 } 1283 1284 /** 1285 * Gets the value of the parameter indicated by key. 1286 * @param key key indicates the parameter to get. 1287 * @return value of the parameter. 1288 * {@hide} 1289 */ 1290 public String getStringParameter(int key) { 1291 Parcel p = Parcel.obtain(); 1292 getParameter(key, p); 1293 return p.readString(); 1294 } 1295 1296 /** 1297 * Gets the value of the parameter indicated by key. 1298 * @param key key indicates the parameter to get. 1299 * @return value of the parameter. 1300 * {@hide} 1301 */ 1302 public int getIntParameter(int key) { 1303 Parcel p = Parcel.obtain(); 1304 getParameter(key, p); 1305 return p.readInt(); 1306 } 1307 1308 /** 1309 * Sets the send level of the player to the attached auxiliary effect 1310 * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0. 1311 * <p>By default the send level is 0, so even if an effect is attached to the player 1312 * this method must be called for the effect to be applied. 1313 * <p>Note that the passed level value is a raw scalar. UI controls should be scaled 1314 * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB, 1315 * so an appropriate conversion from linear UI input x to level is: 1316 * x == 0 -> level = 0 1317 * 0 < x <= R -> level = 10^(72*(x-R)/20/R) 1318 * @param level send level scalar 1319 */ 1320 public native void setAuxEffectSendLevel(float level); 1321 1322 /** 1323 * @param request Parcel destinated to the media player. The 1324 * Interface token must be set to the IMediaPlayer 1325 * one to be routed correctly through the system. 1326 * @param reply[out] Parcel that will contain the reply. 1327 * @return The status code. 1328 */ 1329 private native final int native_invoke(Parcel request, Parcel reply); 1330 1331 1332 /** 1333 * @param update_only If true fetch only the set of metadata that have 1334 * changed since the last invocation of getMetadata. 1335 * The set is built using the unfiltered 1336 * notifications the native player sent to the 1337 * MediaPlayerService during that period of 1338 * time. If false, all the metadatas are considered. 1339 * @param apply_filter If true, once the metadata set has been built based on 1340 * the value update_only, the current filter is applied. 1341 * @param reply[out] On return contains the serialized 1342 * metadata. Valid only if the call was successful. 1343 * @return The status code. 1344 */ 1345 private native final boolean native_getMetadata(boolean update_only, 1346 boolean apply_filter, 1347 Parcel reply); 1348 1349 /** 1350 * @param request Parcel with the 2 serialized lists of allowed 1351 * metadata types followed by the one to be 1352 * dropped. Each list starts with an integer 1353 * indicating the number of metadata type elements. 1354 * @return The status code. 1355 */ 1356 private native final int native_setMetadataFilter(Parcel request); 1357 1358 private static native final void native_init(); 1359 private native final void native_setup(Object mediaplayer_this); 1360 private native final void native_finalize(); 1361 1362 /** 1363 * @param reply Parcel with audio/video duration info for battery 1364 tracking usage 1365 * @return The status code. 1366 * {@hide} 1367 */ 1368 public native static int native_pullBatteryData(Parcel reply); 1369 1370 @Override 1371 protected void finalize() { native_finalize(); } 1372 1373 /* Do not change these values without updating their counterparts 1374 * in include/media/mediaplayer.h! 1375 */ 1376 private static final int MEDIA_NOP = 0; // interface test message 1377 private static final int MEDIA_PREPARED = 1; 1378 private static final int MEDIA_PLAYBACK_COMPLETE = 2; 1379 private static final int MEDIA_BUFFERING_UPDATE = 3; 1380 private static final int MEDIA_SEEK_COMPLETE = 4; 1381 private static final int MEDIA_SET_VIDEO_SIZE = 5; 1382 private static final int MEDIA_TIMED_TEXT = 99; 1383 private static final int MEDIA_ERROR = 100; 1384 private static final int MEDIA_INFO = 200; 1385 1386 private class EventHandler extends Handler 1387 { 1388 private MediaPlayer mMediaPlayer; 1389 1390 public EventHandler(MediaPlayer mp, Looper looper) { 1391 super(looper); 1392 mMediaPlayer = mp; 1393 } 1394 1395 @Override 1396 public void handleMessage(Message msg) { 1397 if (mMediaPlayer.mNativeContext == 0) { 1398 Log.w(TAG, "mediaplayer went away with unhandled events"); 1399 return; 1400 } 1401 switch(msg.what) { 1402 case MEDIA_PREPARED: 1403 if (mOnPreparedListener != null) 1404 mOnPreparedListener.onPrepared(mMediaPlayer); 1405 return; 1406 1407 case MEDIA_PLAYBACK_COMPLETE: 1408 if (mOnCompletionListener != null) 1409 mOnCompletionListener.onCompletion(mMediaPlayer); 1410 stayAwake(false); 1411 return; 1412 1413 case MEDIA_BUFFERING_UPDATE: 1414 if (mOnBufferingUpdateListener != null) 1415 mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1); 1416 return; 1417 1418 case MEDIA_SEEK_COMPLETE: 1419 if (mOnSeekCompleteListener != null) 1420 mOnSeekCompleteListener.onSeekComplete(mMediaPlayer); 1421 return; 1422 1423 case MEDIA_SET_VIDEO_SIZE: 1424 if (mOnVideoSizeChangedListener != null) 1425 mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2); 1426 return; 1427 1428 case MEDIA_ERROR: 1429 // For PV specific error values (msg.arg2) look in 1430 // opencore/pvmi/pvmf/include/pvmf_return_codes.h 1431 Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")"); 1432 boolean error_was_handled = false; 1433 if (mOnErrorListener != null) { 1434 error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2); 1435 } 1436 if (mOnCompletionListener != null && ! error_was_handled) { 1437 mOnCompletionListener.onCompletion(mMediaPlayer); 1438 } 1439 stayAwake(false); 1440 return; 1441 1442 case MEDIA_INFO: 1443 if (msg.arg1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) { 1444 Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")"); 1445 } 1446 if (mOnInfoListener != null) { 1447 mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2); 1448 } 1449 // No real default action so far. 1450 return; 1451 case MEDIA_TIMED_TEXT: 1452 if (mOnTimedTextListener != null) { 1453 mOnTimedTextListener.onTimedText(mMediaPlayer, (String)msg.obj); 1454 } 1455 return; 1456 1457 case MEDIA_NOP: // interface test message - ignore 1458 break; 1459 1460 default: 1461 Log.e(TAG, "Unknown message type " + msg.what); 1462 return; 1463 } 1464 } 1465 } 1466 1467 /** 1468 * Called from native code when an interesting event happens. This method 1469 * just uses the EventHandler system to post the event back to the main app thread. 1470 * We use a weak reference to the original MediaPlayer object so that the native 1471 * code is safe from the object disappearing from underneath it. (This is 1472 * the cookie passed to native_setup().) 1473 */ 1474 private static void postEventFromNative(Object mediaplayer_ref, 1475 int what, int arg1, int arg2, Object obj) 1476 { 1477 MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get(); 1478 if (mp == null) { 1479 return; 1480 } 1481 1482 if (mp.mEventHandler != null) { 1483 Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj); 1484 mp.mEventHandler.sendMessage(m); 1485 } 1486 } 1487 1488 /** 1489 * Interface definition for a callback to be invoked when the media 1490 * source is ready for playback. 1491 */ 1492 public interface OnPreparedListener 1493 { 1494 /** 1495 * Called when the media file is ready for playback. 1496 * 1497 * @param mp the MediaPlayer that is ready for playback 1498 */ 1499 void onPrepared(MediaPlayer mp); 1500 } 1501 1502 /** 1503 * Register a callback to be invoked when the media source is ready 1504 * for playback. 1505 * 1506 * @param listener the callback that will be run 1507 */ 1508 public void setOnPreparedListener(OnPreparedListener listener) 1509 { 1510 mOnPreparedListener = listener; 1511 } 1512 1513 private OnPreparedListener mOnPreparedListener; 1514 1515 /** 1516 * Interface definition for a callback to be invoked when playback of 1517 * a media source has completed. 1518 */ 1519 public interface OnCompletionListener 1520 { 1521 /** 1522 * Called when the end of a media source is reached during playback. 1523 * 1524 * @param mp the MediaPlayer that reached the end of the file 1525 */ 1526 void onCompletion(MediaPlayer mp); 1527 } 1528 1529 /** 1530 * Register a callback to be invoked when the end of a media source 1531 * has been reached during playback. 1532 * 1533 * @param listener the callback that will be run 1534 */ 1535 public void setOnCompletionListener(OnCompletionListener listener) 1536 { 1537 mOnCompletionListener = listener; 1538 } 1539 1540 private OnCompletionListener mOnCompletionListener; 1541 1542 /** 1543 * Interface definition of a callback to be invoked indicating buffering 1544 * status of a media resource being streamed over the network. 1545 */ 1546 public interface OnBufferingUpdateListener 1547 { 1548 /** 1549 * Called to update status in buffering a media stream received through 1550 * progressive HTTP download. The received buffering percentage 1551 * indicates how much of the content has been buffered or played. 1552 * For example a buffering update of 80 percent when half the content 1553 * has already been played indicates that the next 30 percent of the 1554 * content to play has been buffered. 1555 * 1556 * @param mp the MediaPlayer the update pertains to 1557 * @param percent the percentage (0-100) of the content 1558 * that has been buffered or played thus far 1559 */ 1560 void onBufferingUpdate(MediaPlayer mp, int percent); 1561 } 1562 1563 /** 1564 * Register a callback to be invoked when the status of a network 1565 * stream's buffer has changed. 1566 * 1567 * @param listener the callback that will be run. 1568 */ 1569 public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener) 1570 { 1571 mOnBufferingUpdateListener = listener; 1572 } 1573 1574 private OnBufferingUpdateListener mOnBufferingUpdateListener; 1575 1576 /** 1577 * Interface definition of a callback to be invoked indicating 1578 * the completion of a seek operation. 1579 */ 1580 public interface OnSeekCompleteListener 1581 { 1582 /** 1583 * Called to indicate the completion of a seek operation. 1584 * 1585 * @param mp the MediaPlayer that issued the seek operation 1586 */ 1587 public void onSeekComplete(MediaPlayer mp); 1588 } 1589 1590 /** 1591 * Register a callback to be invoked when a seek operation has been 1592 * completed. 1593 * 1594 * @param listener the callback that will be run 1595 */ 1596 public void setOnSeekCompleteListener(OnSeekCompleteListener listener) 1597 { 1598 mOnSeekCompleteListener = listener; 1599 } 1600 1601 private OnSeekCompleteListener mOnSeekCompleteListener; 1602 1603 /** 1604 * Interface definition of a callback to be invoked when the 1605 * video size is first known or updated 1606 */ 1607 public interface OnVideoSizeChangedListener 1608 { 1609 /** 1610 * Called to indicate the video size 1611 * 1612 * @param mp the MediaPlayer associated with this callback 1613 * @param width the width of the video 1614 * @param height the height of the video 1615 */ 1616 public void onVideoSizeChanged(MediaPlayer mp, int width, int height); 1617 } 1618 1619 /** 1620 * Register a callback to be invoked when the video size is 1621 * known or updated. 1622 * 1623 * @param listener the callback that will be run 1624 */ 1625 public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener) 1626 { 1627 mOnVideoSizeChangedListener = listener; 1628 } 1629 1630 private OnVideoSizeChangedListener mOnVideoSizeChangedListener; 1631 1632 /** 1633 * Interface definition of a callback to be invoked when a 1634 * timed text is available for display. 1635 * {@hide} 1636 */ 1637 public interface OnTimedTextListener 1638 { 1639 /** 1640 * Called to indicate the video size 1641 * 1642 * @param mp the MediaPlayer associated with this callback 1643 * @param text the timed text sample which contains the 1644 * text needed to be displayed. 1645 * {@hide} 1646 */ 1647 public void onTimedText(MediaPlayer mp, String text); 1648 } 1649 1650 /** 1651 * Register a callback to be invoked when a timed text is available 1652 * for display. 1653 * 1654 * @param listener the callback that will be run 1655 * {@hide} 1656 */ 1657 public void setOnTimedTextListener(OnTimedTextListener listener) 1658 { 1659 mOnTimedTextListener = listener; 1660 } 1661 1662 private OnTimedTextListener mOnTimedTextListener; 1663 1664 1665 /* Do not change these values without updating their counterparts 1666 * in include/media/mediaplayer.h! 1667 */ 1668 /** Unspecified media player error. 1669 * @see android.media.MediaPlayer.OnErrorListener 1670 */ 1671 public static final int MEDIA_ERROR_UNKNOWN = 1; 1672 1673 /** Media server died. In this case, the application must release the 1674 * MediaPlayer object and instantiate a new one. 1675 * @see android.media.MediaPlayer.OnErrorListener 1676 */ 1677 public static final int MEDIA_ERROR_SERVER_DIED = 100; 1678 1679 /** The video is streamed and its container is not valid for progressive 1680 * playback i.e the video's index (e.g moov atom) is not at the start of the 1681 * file. 1682 * @see android.media.MediaPlayer.OnErrorListener 1683 */ 1684 public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200; 1685 1686 /** 1687 * Interface definition of a callback to be invoked when there 1688 * has been an error during an asynchronous operation (other errors 1689 * will throw exceptions at method call time). 1690 */ 1691 public interface OnErrorListener 1692 { 1693 /** 1694 * Called to indicate an error. 1695 * 1696 * @param mp the MediaPlayer the error pertains to 1697 * @param what the type of error that has occurred: 1698 * <ul> 1699 * <li>{@link #MEDIA_ERROR_UNKNOWN} 1700 * <li>{@link #MEDIA_ERROR_SERVER_DIED} 1701 * </ul> 1702 * @param extra an extra code, specific to the error. Typically 1703 * implementation dependant. 1704 * @return True if the method handled the error, false if it didn't. 1705 * Returning false, or not having an OnErrorListener at all, will 1706 * cause the OnCompletionListener to be called. 1707 */ 1708 boolean onError(MediaPlayer mp, int what, int extra); 1709 } 1710 1711 /** 1712 * Register a callback to be invoked when an error has happened 1713 * during an asynchronous operation. 1714 * 1715 * @param listener the callback that will be run 1716 */ 1717 public void setOnErrorListener(OnErrorListener listener) 1718 { 1719 mOnErrorListener = listener; 1720 } 1721 1722 private OnErrorListener mOnErrorListener; 1723 1724 1725 /* Do not change these values without updating their counterparts 1726 * in include/media/mediaplayer.h! 1727 */ 1728 /** Unspecified media player info. 1729 * @see android.media.MediaPlayer.OnInfoListener 1730 */ 1731 public static final int MEDIA_INFO_UNKNOWN = 1; 1732 1733 /** The video is too complex for the decoder: it can't decode frames fast 1734 * enough. Possibly only the audio plays fine at this stage. 1735 * @see android.media.MediaPlayer.OnInfoListener 1736 */ 1737 public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; 1738 1739 /** MediaPlayer is temporarily pausing playback internally in order to 1740 * buffer more data. 1741 * @see android.media.MediaPlayer.OnInfoListener 1742 */ 1743 public static final int MEDIA_INFO_BUFFERING_START = 701; 1744 1745 /** MediaPlayer is resuming playback after filling buffers. 1746 * @see android.media.MediaPlayer.OnInfoListener 1747 */ 1748 public static final int MEDIA_INFO_BUFFERING_END = 702; 1749 1750 /** Bad interleaving means that a media has been improperly interleaved or 1751 * not interleaved at all, e.g has all the video samples first then all the 1752 * audio ones. Video is playing but a lot of disk seeks may be happening. 1753 * @see android.media.MediaPlayer.OnInfoListener 1754 */ 1755 public static final int MEDIA_INFO_BAD_INTERLEAVING = 800; 1756 1757 /** The media cannot be seeked (e.g live stream) 1758 * @see android.media.MediaPlayer.OnInfoListener 1759 */ 1760 public static final int MEDIA_INFO_NOT_SEEKABLE = 801; 1761 1762 /** A new set of metadata is available. 1763 * @see android.media.MediaPlayer.OnInfoListener 1764 */ 1765 public static final int MEDIA_INFO_METADATA_UPDATE = 802; 1766 1767 /** 1768 * Interface definition of a callback to be invoked to communicate some 1769 * info and/or warning about the media or its playback. 1770 */ 1771 public interface OnInfoListener 1772 { 1773 /** 1774 * Called to indicate an info or a warning. 1775 * 1776 * @param mp the MediaPlayer the info pertains to. 1777 * @param what the type of info or warning. 1778 * <ul> 1779 * <li>{@link #MEDIA_INFO_UNKNOWN} 1780 * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING} 1781 * <li>{@link #MEDIA_INFO_BUFFERING_START} 1782 * <li>{@link #MEDIA_INFO_BUFFERING_END} 1783 * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING} 1784 * <li>{@link #MEDIA_INFO_NOT_SEEKABLE} 1785 * <li>{@link #MEDIA_INFO_METADATA_UPDATE} 1786 * </ul> 1787 * @param extra an extra code, specific to the info. Typically 1788 * implementation dependant. 1789 * @return True if the method handled the info, false if it didn't. 1790 * Returning false, or not having an OnErrorListener at all, will 1791 * cause the info to be discarded. 1792 */ 1793 boolean onInfo(MediaPlayer mp, int what, int extra); 1794 } 1795 1796 /** 1797 * Register a callback to be invoked when an info/warning is available. 1798 * 1799 * @param listener the callback that will be run 1800 */ 1801 public void setOnInfoListener(OnInfoListener listener) 1802 { 1803 mOnInfoListener = listener; 1804 } 1805 1806 private OnInfoListener mOnInfoListener; 1807 1808} 1809