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