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