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