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