MediaPlayer.java revision 84b832054552e00257bb04997143ca33d6d100be
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 * Set the MediaPlayer to start when this MediaPlayer finishes playback 1152 * (i.e. reaches the end of the stream). 1153 * The media framework will attempt to transition from this player to 1154 * the next as seamlessly as possible. The next player can be set at 1155 * any time before completion. The next player must be prepared by the 1156 * app, and the application should not call start() on it. 1157 * The next MediaPlayer must be different from 'this'. An exception 1158 * will be thrown if next == this. 1159 * The application may call setNextMediaPlayer(null) to indicate no 1160 * next player should be started at the end of playback. 1161 * If the current player is looping, it will keep looping and the next 1162 * player will not be started. 1163 * 1164 * @param next the player to start after this one completes playback. 1165 * 1166 * @hide 1167 */ 1168 public native void setNextMediaPlayer(MediaPlayer next); 1169 1170 /** 1171 * Releases resources associated with this MediaPlayer object. 1172 * It is considered good practice to call this method when you're 1173 * done using the MediaPlayer. In particular, whenever an Activity 1174 * of an application is paused (its onPause() method is called), 1175 * or stopped (its onStop() method is called), this method should be 1176 * invoked to release the MediaPlayer object, unless the application 1177 * has a special need to keep the object around. In addition to 1178 * unnecessary resources (such as memory and instances of codecs) 1179 * being held, failure to call this method immediately if a 1180 * MediaPlayer object is no longer needed may also lead to 1181 * continuous battery consumption for mobile devices, and playback 1182 * failure for other applications if no multiple instances of the 1183 * same codec are supported on a device. Even if multiple instances 1184 * of the same codec are supported, some performance degradation 1185 * may be expected when unnecessary multiple instances are used 1186 * at the same time. 1187 */ 1188 public void release() { 1189 stayAwake(false); 1190 updateSurfaceScreenOn(); 1191 mOnPreparedListener = null; 1192 mOnBufferingUpdateListener = null; 1193 mOnCompletionListener = null; 1194 mOnSeekCompleteListener = null; 1195 mOnErrorListener = null; 1196 mOnInfoListener = null; 1197 mOnVideoSizeChangedListener = null; 1198 mOnTimedTextListener = null; 1199 _release(); 1200 } 1201 1202 private native void _release(); 1203 1204 /** 1205 * Resets the MediaPlayer to its uninitialized state. After calling 1206 * this method, you will have to initialize it again by setting the 1207 * data source and calling prepare(). 1208 */ 1209 public void reset() { 1210 stayAwake(false); 1211 _reset(); 1212 // make sure none of the listeners get called anymore 1213 mEventHandler.removeCallbacksAndMessages(null); 1214 } 1215 1216 private native void _reset(); 1217 1218 /** 1219 * Sets the audio stream type for this MediaPlayer. See {@link AudioManager} 1220 * for a list of stream types. Must call this method before prepare() or 1221 * prepareAsync() in order for the target stream type to become effective 1222 * thereafter. 1223 * 1224 * @param streamtype the audio stream type 1225 * @see android.media.AudioManager 1226 */ 1227 public native void setAudioStreamType(int streamtype); 1228 1229 /** 1230 * Sets the player to be looping or non-looping. 1231 * 1232 * @param looping whether to loop or not 1233 */ 1234 public native void setLooping(boolean looping); 1235 1236 /** 1237 * Checks whether the MediaPlayer is looping or non-looping. 1238 * 1239 * @return true if the MediaPlayer is currently looping, false otherwise 1240 */ 1241 public native boolean isLooping(); 1242 1243 /** 1244 * Sets the volume on this player. 1245 * This API is recommended for balancing the output of audio streams 1246 * within an application. Unless you are writing an application to 1247 * control user settings, this API should be used in preference to 1248 * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of 1249 * a particular type. Note that the passed volume values are raw scalars. 1250 * UI controls should be scaled logarithmically. 1251 * 1252 * @param leftVolume left volume scalar 1253 * @param rightVolume right volume scalar 1254 */ 1255 public native void setVolume(float leftVolume, float rightVolume); 1256 1257 /** 1258 * Currently not implemented, returns null. 1259 * @deprecated 1260 * @hide 1261 */ 1262 public native Bitmap getFrameAt(int msec) throws IllegalStateException; 1263 1264 /** 1265 * Sets the audio session ID. 1266 * 1267 * @param sessionId the audio session ID. 1268 * The audio session ID is a system wide unique identifier for the audio stream played by 1269 * this MediaPlayer instance. 1270 * The primary use of the audio session ID is to associate audio effects to a particular 1271 * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect, 1272 * this effect will be applied only to the audio content of media players within the same 1273 * audio session and not to the output mix. 1274 * When created, a MediaPlayer instance automatically generates its own audio session ID. 1275 * However, it is possible to force this player to be part of an already existing audio session 1276 * by calling this method. 1277 * This method must be called before one of the overloaded <code> setDataSource </code> methods. 1278 * @throws IllegalStateException if it is called in an invalid state 1279 */ 1280 public native void setAudioSessionId(int sessionId) throws IllegalArgumentException, IllegalStateException; 1281 1282 /** 1283 * Returns the audio session ID. 1284 * 1285 * @return the audio session ID. {@see #setAudioSessionId(int)} 1286 * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed. 1287 */ 1288 public native int getAudioSessionId(); 1289 1290 /** 1291 * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation 1292 * effect which can be applied on any sound source that directs a certain amount of its 1293 * energy to this effect. This amount is defined by setAuxEffectSendLevel(). 1294 * {@see #setAuxEffectSendLevel(float)}. 1295 * <p>After creating an auxiliary effect (e.g. 1296 * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with 1297 * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method 1298 * to attach the player to the effect. 1299 * <p>To detach the effect from the player, call this method with a null effect id. 1300 * <p>This method must be called after one of the overloaded <code> setDataSource </code> 1301 * methods. 1302 * @param effectId system wide unique id of the effect to attach 1303 */ 1304 public native void attachAuxEffect(int effectId); 1305 1306 /* Do not change these values (starting with KEY_PARAMETER) without updating 1307 * their counterparts in include/media/mediaplayer.h! 1308 */ 1309 /* 1310 * Key used in setParameter method. 1311 * Indicates the index of the timed text track to be enabled/disabled. 1312 * The index includes both the in-band and out-of-band timed text. 1313 * The index should start from in-band text if any. Application can retrieve the number 1314 * of in-band text tracks by using MediaMetadataRetriever::extractMetadata(). 1315 * Note it might take a few hundred ms to scan an out-of-band text file 1316 * before displaying it. 1317 */ 1318 private static final int KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX = 1000; 1319 /* 1320 * Key used in setParameter method. 1321 * Used to add out-of-band timed text source path. 1322 * Application can add multiple text sources by calling setParameter() with 1323 * KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE multiple times. 1324 */ 1325 private static final int KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE = 1001; 1326 1327 // There are currently no defined keys usable from Java with get*Parameter. 1328 // But if any keys are defined, the order must be kept in sync with include/media/mediaplayer.h. 1329 // private static final int KEY_PARAMETER_... = ...; 1330 1331 /** 1332 * Sets the parameter indicated by key. 1333 * @param key key indicates the parameter to be set. 1334 * @param value value of the parameter to be set. 1335 * @return true if the parameter is set successfully, false otherwise 1336 * {@hide} 1337 */ 1338 public native boolean setParameter(int key, Parcel value); 1339 1340 /** 1341 * Sets the parameter indicated by key. 1342 * @param key key indicates the parameter to be set. 1343 * @param value value of the parameter to be set. 1344 * @return true if the parameter is set successfully, false otherwise 1345 * {@hide} 1346 */ 1347 public boolean setParameter(int key, String value) { 1348 Parcel p = Parcel.obtain(); 1349 p.writeString(value); 1350 boolean ret = setParameter(key, p); 1351 p.recycle(); 1352 return ret; 1353 } 1354 1355 /** 1356 * Sets the parameter indicated by key. 1357 * @param key key indicates the parameter to be set. 1358 * @param value value of the parameter to be set. 1359 * @return true if the parameter is set successfully, false otherwise 1360 * {@hide} 1361 */ 1362 public boolean setParameter(int key, int value) { 1363 Parcel p = Parcel.obtain(); 1364 p.writeInt(value); 1365 boolean ret = setParameter(key, p); 1366 p.recycle(); 1367 return ret; 1368 } 1369 1370 /** 1371 * Gets the value of the parameter indicated by key. 1372 * @param key key indicates the parameter to get. 1373 * @param reply value of the parameter to get. 1374 */ 1375 private native void getParameter(int key, Parcel reply); 1376 1377 /** 1378 * Gets the value of the parameter indicated by key. 1379 * The caller is responsible for recycling the returned parcel. 1380 * @param key key indicates the parameter to get. 1381 * @return value of the parameter. 1382 * {@hide} 1383 */ 1384 public Parcel getParcelParameter(int key) { 1385 Parcel p = Parcel.obtain(); 1386 getParameter(key, p); 1387 return p; 1388 } 1389 1390 /** 1391 * Gets the value of the parameter indicated by key. 1392 * @param key key indicates the parameter to get. 1393 * @return value of the parameter. 1394 * {@hide} 1395 */ 1396 public String getStringParameter(int key) { 1397 Parcel p = Parcel.obtain(); 1398 getParameter(key, p); 1399 String ret = p.readString(); 1400 p.recycle(); 1401 return ret; 1402 } 1403 1404 /** 1405 * Gets the value of the parameter indicated by key. 1406 * @param key key indicates the parameter to get. 1407 * @return value of the parameter. 1408 * {@hide} 1409 */ 1410 public int getIntParameter(int key) { 1411 Parcel p = Parcel.obtain(); 1412 getParameter(key, p); 1413 int ret = p.readInt(); 1414 p.recycle(); 1415 return ret; 1416 } 1417 1418 /** 1419 * Sets the send level of the player to the attached auxiliary effect 1420 * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0. 1421 * <p>By default the send level is 0, so even if an effect is attached to the player 1422 * this method must be called for the effect to be applied. 1423 * <p>Note that the passed level value is a raw scalar. UI controls should be scaled 1424 * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB, 1425 * so an appropriate conversion from linear UI input x to level is: 1426 * x == 0 -> level = 0 1427 * 0 < x <= R -> level = 10^(72*(x-R)/20/R) 1428 * @param level send level scalar 1429 */ 1430 public native void setAuxEffectSendLevel(float level); 1431 1432 /** 1433 * @param request Parcel destinated to the media player. The 1434 * Interface token must be set to the IMediaPlayer 1435 * one to be routed correctly through the system. 1436 * @param reply[out] Parcel that will contain the reply. 1437 * @return The status code. 1438 */ 1439 private native final int native_invoke(Parcel request, Parcel reply); 1440 1441 1442 /** 1443 * @param update_only If true fetch only the set of metadata that have 1444 * changed since the last invocation of getMetadata. 1445 * The set is built using the unfiltered 1446 * notifications the native player sent to the 1447 * MediaPlayerService during that period of 1448 * time. If false, all the metadatas are considered. 1449 * @param apply_filter If true, once the metadata set has been built based on 1450 * the value update_only, the current filter is applied. 1451 * @param reply[out] On return contains the serialized 1452 * metadata. Valid only if the call was successful. 1453 * @return The status code. 1454 */ 1455 private native final boolean native_getMetadata(boolean update_only, 1456 boolean apply_filter, 1457 Parcel reply); 1458 1459 /** 1460 * @param request Parcel with the 2 serialized lists of allowed 1461 * metadata types followed by the one to be 1462 * dropped. Each list starts with an integer 1463 * indicating the number of metadata type elements. 1464 * @return The status code. 1465 */ 1466 private native final int native_setMetadataFilter(Parcel request); 1467 1468 private static native final void native_init(); 1469 private native final void native_setup(Object mediaplayer_this); 1470 private native final void native_finalize(); 1471 1472 /** 1473 * @param index The index of the text track to be turned on. 1474 * @return true if the text track is enabled successfully. 1475 * {@hide} 1476 */ 1477 public boolean enableTimedTextTrackIndex(int index) { 1478 if (index < 0) { 1479 return false; 1480 } 1481 return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, index); 1482 } 1483 1484 /** 1485 * Enables the first timed text track if any. 1486 * @return true if the text track is enabled successfully 1487 * {@hide} 1488 */ 1489 public boolean enableTimedText() { 1490 return enableTimedTextTrackIndex(0); 1491 } 1492 1493 /** 1494 * Disables timed text display. 1495 * @return true if the text track is disabled successfully. 1496 * {@hide} 1497 */ 1498 public boolean disableTimedText() { 1499 return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, -1); 1500 } 1501 1502 /** 1503 * @param reply Parcel with audio/video duration info for battery 1504 tracking usage 1505 * @return The status code. 1506 * {@hide} 1507 */ 1508 public native static int native_pullBatteryData(Parcel reply); 1509 1510 /** 1511 * Sets the target UDP re-transmit endpoint for the low level player. 1512 * Generally, the address portion of the endpoint is an IP multicast 1513 * address, although a unicast address would be equally valid. When a valid 1514 * retransmit endpoint has been set, the media player will not decode and 1515 * render the media presentation locally. Instead, the player will attempt 1516 * to re-multiplex its media data using the Android@Home RTP profile and 1517 * re-transmit to the target endpoint. Receiver devices (which may be 1518 * either the same as the transmitting device or different devices) may 1519 * instantiate, prepare, and start a receiver player using a setDataSource 1520 * URL of the form... 1521 * 1522 * aahRX://<multicastIP>:<port> 1523 * 1524 * to receive, decode and render the re-transmitted content. 1525 * 1526 * setRetransmitEndpoint may only be called before setDataSource has been 1527 * called; while the player is in the Idle state. 1528 * 1529 * @param endpoint the address and UDP port of the re-transmission target or 1530 * null if no re-transmission is to be performed. 1531 * @throws IllegalStateException if it is called in an invalid state 1532 * @throws IllegalArgumentException if the retransmit endpoint is supplied, 1533 * but invalid. 1534 * 1535 * {@hide} pending API council 1536 */ 1537 public void setRetransmitEndpoint(InetSocketAddress endpoint) 1538 throws IllegalStateException, IllegalArgumentException 1539 { 1540 String addrString = null; 1541 int port = 0; 1542 1543 if (null != endpoint) { 1544 addrString = endpoint.getAddress().getHostAddress(); 1545 port = endpoint.getPort(); 1546 } 1547 1548 int ret = native_setRetransmitEndpoint(addrString, port); 1549 if (ret != 0) { 1550 throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret); 1551 } 1552 } 1553 1554 private native final int native_setRetransmitEndpoint(String addrString, int port); 1555 1556 @Override 1557 protected void finalize() { native_finalize(); } 1558 1559 /* Do not change these values without updating their counterparts 1560 * in include/media/mediaplayer.h! 1561 */ 1562 private static final int MEDIA_NOP = 0; // interface test message 1563 private static final int MEDIA_PREPARED = 1; 1564 private static final int MEDIA_PLAYBACK_COMPLETE = 2; 1565 private static final int MEDIA_BUFFERING_UPDATE = 3; 1566 private static final int MEDIA_SEEK_COMPLETE = 4; 1567 private static final int MEDIA_SET_VIDEO_SIZE = 5; 1568 private static final int MEDIA_TIMED_TEXT = 99; 1569 private static final int MEDIA_ERROR = 100; 1570 private static final int MEDIA_INFO = 200; 1571 1572 private class EventHandler extends Handler 1573 { 1574 private MediaPlayer mMediaPlayer; 1575 1576 public EventHandler(MediaPlayer mp, Looper looper) { 1577 super(looper); 1578 mMediaPlayer = mp; 1579 } 1580 1581 @Override 1582 public void handleMessage(Message msg) { 1583 if (mMediaPlayer.mNativeContext == 0) { 1584 Log.w(TAG, "mediaplayer went away with unhandled events"); 1585 return; 1586 } 1587 switch(msg.what) { 1588 case MEDIA_PREPARED: 1589 if (mOnPreparedListener != null) 1590 mOnPreparedListener.onPrepared(mMediaPlayer); 1591 return; 1592 1593 case MEDIA_PLAYBACK_COMPLETE: 1594 if (mOnCompletionListener != null) 1595 mOnCompletionListener.onCompletion(mMediaPlayer); 1596 stayAwake(false); 1597 return; 1598 1599 case MEDIA_BUFFERING_UPDATE: 1600 if (mOnBufferingUpdateListener != null) 1601 mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1); 1602 return; 1603 1604 case MEDIA_SEEK_COMPLETE: 1605 if (mOnSeekCompleteListener != null) 1606 mOnSeekCompleteListener.onSeekComplete(mMediaPlayer); 1607 return; 1608 1609 case MEDIA_SET_VIDEO_SIZE: 1610 if (mOnVideoSizeChangedListener != null) 1611 mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2); 1612 return; 1613 1614 case MEDIA_ERROR: 1615 // For PV specific error values (msg.arg2) look in 1616 // opencore/pvmi/pvmf/include/pvmf_return_codes.h 1617 Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")"); 1618 boolean error_was_handled = false; 1619 if (mOnErrorListener != null) { 1620 error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2); 1621 } 1622 if (mOnCompletionListener != null && ! error_was_handled) { 1623 mOnCompletionListener.onCompletion(mMediaPlayer); 1624 } 1625 stayAwake(false); 1626 return; 1627 1628 case MEDIA_INFO: 1629 if (msg.arg1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) { 1630 Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")"); 1631 } 1632 if (mOnInfoListener != null) { 1633 mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2); 1634 } 1635 // No real default action so far. 1636 return; 1637 case MEDIA_TIMED_TEXT: 1638 if (mOnTimedTextListener != null) { 1639 if (msg.obj == null) { 1640 mOnTimedTextListener.onTimedText(mMediaPlayer, null); 1641 } else { 1642 if (msg.obj instanceof byte[]) { 1643 TimedText text = new TimedText((byte[])(msg.obj)); 1644 mOnTimedTextListener.onTimedText(mMediaPlayer, text); 1645 } 1646 } 1647 } 1648 return; 1649 1650 case MEDIA_NOP: // interface test message - ignore 1651 break; 1652 1653 default: 1654 Log.e(TAG, "Unknown message type " + msg.what); 1655 return; 1656 } 1657 } 1658 } 1659 1660 /** 1661 * Called from native code when an interesting event happens. This method 1662 * just uses the EventHandler system to post the event back to the main app thread. 1663 * We use a weak reference to the original MediaPlayer object so that the native 1664 * code is safe from the object disappearing from underneath it. (This is 1665 * the cookie passed to native_setup().) 1666 */ 1667 private static void postEventFromNative(Object mediaplayer_ref, 1668 int what, int arg1, int arg2, Object obj) 1669 { 1670 MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get(); 1671 if (mp == null) { 1672 return; 1673 } 1674 1675 if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) { 1676 // this acquires the wakelock if needed, and sets the client side state 1677 mp.start(); 1678 } 1679 if (mp.mEventHandler != null) { 1680 Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj); 1681 mp.mEventHandler.sendMessage(m); 1682 } 1683 } 1684 1685 /** 1686 * Interface definition for a callback to be invoked when the media 1687 * source is ready for playback. 1688 */ 1689 public interface OnPreparedListener 1690 { 1691 /** 1692 * Called when the media file is ready for playback. 1693 * 1694 * @param mp the MediaPlayer that is ready for playback 1695 */ 1696 void onPrepared(MediaPlayer mp); 1697 } 1698 1699 /** 1700 * Register a callback to be invoked when the media source is ready 1701 * for playback. 1702 * 1703 * @param listener the callback that will be run 1704 */ 1705 public void setOnPreparedListener(OnPreparedListener listener) 1706 { 1707 mOnPreparedListener = listener; 1708 } 1709 1710 private OnPreparedListener mOnPreparedListener; 1711 1712 /** 1713 * Interface definition for a callback to be invoked when playback of 1714 * a media source has completed. 1715 */ 1716 public interface OnCompletionListener 1717 { 1718 /** 1719 * Called when the end of a media source is reached during playback. 1720 * 1721 * @param mp the MediaPlayer that reached the end of the file 1722 */ 1723 void onCompletion(MediaPlayer mp); 1724 } 1725 1726 /** 1727 * Register a callback to be invoked when the end of a media source 1728 * has been reached during playback. 1729 * 1730 * @param listener the callback that will be run 1731 */ 1732 public void setOnCompletionListener(OnCompletionListener listener) 1733 { 1734 mOnCompletionListener = listener; 1735 } 1736 1737 private OnCompletionListener mOnCompletionListener; 1738 1739 /** 1740 * Interface definition of a callback to be invoked indicating buffering 1741 * status of a media resource being streamed over the network. 1742 */ 1743 public interface OnBufferingUpdateListener 1744 { 1745 /** 1746 * Called to update status in buffering a media stream received through 1747 * progressive HTTP download. The received buffering percentage 1748 * indicates how much of the content has been buffered or played. 1749 * For example a buffering update of 80 percent when half the content 1750 * has already been played indicates that the next 30 percent of the 1751 * content to play has been buffered. 1752 * 1753 * @param mp the MediaPlayer the update pertains to 1754 * @param percent the percentage (0-100) of the content 1755 * that has been buffered or played thus far 1756 */ 1757 void onBufferingUpdate(MediaPlayer mp, int percent); 1758 } 1759 1760 /** 1761 * Register a callback to be invoked when the status of a network 1762 * stream's buffer has changed. 1763 * 1764 * @param listener the callback that will be run. 1765 */ 1766 public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener) 1767 { 1768 mOnBufferingUpdateListener = listener; 1769 } 1770 1771 private OnBufferingUpdateListener mOnBufferingUpdateListener; 1772 1773 /** 1774 * Interface definition of a callback to be invoked indicating 1775 * the completion of a seek operation. 1776 */ 1777 public interface OnSeekCompleteListener 1778 { 1779 /** 1780 * Called to indicate the completion of a seek operation. 1781 * 1782 * @param mp the MediaPlayer that issued the seek operation 1783 */ 1784 public void onSeekComplete(MediaPlayer mp); 1785 } 1786 1787 /** 1788 * Register a callback to be invoked when a seek operation has been 1789 * completed. 1790 * 1791 * @param listener the callback that will be run 1792 */ 1793 public void setOnSeekCompleteListener(OnSeekCompleteListener listener) 1794 { 1795 mOnSeekCompleteListener = listener; 1796 } 1797 1798 private OnSeekCompleteListener mOnSeekCompleteListener; 1799 1800 /** 1801 * Interface definition of a callback to be invoked when the 1802 * video size is first known or updated 1803 */ 1804 public interface OnVideoSizeChangedListener 1805 { 1806 /** 1807 * Called to indicate the video size 1808 * 1809 * The video size (width and height) could be 0 if there was no video, 1810 * no display surface was set, or the value was not determined yet. 1811 * 1812 * @param mp the MediaPlayer associated with this callback 1813 * @param width the width of the video 1814 * @param height the height of the video 1815 */ 1816 public void onVideoSizeChanged(MediaPlayer mp, int width, int height); 1817 } 1818 1819 /** 1820 * Register a callback to be invoked when the video size is 1821 * known or updated. 1822 * 1823 * @param listener the callback that will be run 1824 */ 1825 public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener) 1826 { 1827 mOnVideoSizeChangedListener = listener; 1828 } 1829 1830 private OnVideoSizeChangedListener mOnVideoSizeChangedListener; 1831 1832 /** 1833 * Interface definition of a callback to be invoked when a 1834 * timed text is available for display. 1835 * {@hide} 1836 */ 1837 public interface OnTimedTextListener 1838 { 1839 /** 1840 * Called to indicate an avaliable timed text 1841 * 1842 * @param mp the MediaPlayer associated with this callback 1843 * @param text the timed text sample which contains the text 1844 * needed to be displayed and the display format. 1845 * {@hide} 1846 */ 1847 public void onTimedText(MediaPlayer mp, TimedText text); 1848 } 1849 1850 /** 1851 * Register a callback to be invoked when a timed text is available 1852 * for display. 1853 * 1854 * @param listener the callback that will be run 1855 * {@hide} 1856 */ 1857 public void setOnTimedTextListener(OnTimedTextListener listener) 1858 { 1859 mOnTimedTextListener = listener; 1860 } 1861 1862 private OnTimedTextListener mOnTimedTextListener; 1863 1864 1865 /* Do not change these values without updating their counterparts 1866 * in include/media/mediaplayer.h! 1867 */ 1868 /** Unspecified media player error. 1869 * @see android.media.MediaPlayer.OnErrorListener 1870 */ 1871 public static final int MEDIA_ERROR_UNKNOWN = 1; 1872 1873 /** Media server died. In this case, the application must release the 1874 * MediaPlayer object and instantiate a new one. 1875 * @see android.media.MediaPlayer.OnErrorListener 1876 */ 1877 public static final int MEDIA_ERROR_SERVER_DIED = 100; 1878 1879 /** The video is streamed and its container is not valid for progressive 1880 * playback i.e the video's index (e.g moov atom) is not at the start of the 1881 * file. 1882 * @see android.media.MediaPlayer.OnErrorListener 1883 */ 1884 public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200; 1885 1886 /** 1887 * Interface definition of a callback to be invoked when there 1888 * has been an error during an asynchronous operation (other errors 1889 * will throw exceptions at method call time). 1890 */ 1891 public interface OnErrorListener 1892 { 1893 /** 1894 * Called to indicate an error. 1895 * 1896 * @param mp the MediaPlayer the error pertains to 1897 * @param what the type of error that has occurred: 1898 * <ul> 1899 * <li>{@link #MEDIA_ERROR_UNKNOWN} 1900 * <li>{@link #MEDIA_ERROR_SERVER_DIED} 1901 * </ul> 1902 * @param extra an extra code, specific to the error. Typically 1903 * implementation dependant. 1904 * @return True if the method handled the error, false if it didn't. 1905 * Returning false, or not having an OnErrorListener at all, will 1906 * cause the OnCompletionListener to be called. 1907 */ 1908 boolean onError(MediaPlayer mp, int what, int extra); 1909 } 1910 1911 /** 1912 * Register a callback to be invoked when an error has happened 1913 * during an asynchronous operation. 1914 * 1915 * @param listener the callback that will be run 1916 */ 1917 public void setOnErrorListener(OnErrorListener listener) 1918 { 1919 mOnErrorListener = listener; 1920 } 1921 1922 private OnErrorListener mOnErrorListener; 1923 1924 1925 /* Do not change these values without updating their counterparts 1926 * in include/media/mediaplayer.h! 1927 */ 1928 /** Unspecified media player info. 1929 * @see android.media.MediaPlayer.OnInfoListener 1930 */ 1931 public static final int MEDIA_INFO_UNKNOWN = 1; 1932 1933 /** The player was started because it was used as the next player for another 1934 * player, which just completed playback. 1935 * @see android.media.MediaPlayer.OnInfoListener 1936 * @hide 1937 */ 1938 public static final int MEDIA_INFO_STARTED_AS_NEXT = 2; 1939 1940 /** The video is too complex for the decoder: it can't decode frames fast 1941 * enough. Possibly only the audio plays fine at this stage. 1942 * @see android.media.MediaPlayer.OnInfoListener 1943 */ 1944 public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; 1945 1946 /** MediaPlayer is temporarily pausing playback internally in order to 1947 * buffer more data. 1948 * @see android.media.MediaPlayer.OnInfoListener 1949 */ 1950 public static final int MEDIA_INFO_BUFFERING_START = 701; 1951 1952 /** MediaPlayer is resuming playback after filling buffers. 1953 * @see android.media.MediaPlayer.OnInfoListener 1954 */ 1955 public static final int MEDIA_INFO_BUFFERING_END = 702; 1956 1957 /** Bad interleaving means that a media has been improperly interleaved or 1958 * not interleaved at all, e.g has all the video samples first then all the 1959 * audio ones. Video is playing but a lot of disk seeks may be happening. 1960 * @see android.media.MediaPlayer.OnInfoListener 1961 */ 1962 public static final int MEDIA_INFO_BAD_INTERLEAVING = 800; 1963 1964 /** The media cannot be seeked (e.g live stream) 1965 * @see android.media.MediaPlayer.OnInfoListener 1966 */ 1967 public static final int MEDIA_INFO_NOT_SEEKABLE = 801; 1968 1969 /** A new set of metadata is available. 1970 * @see android.media.MediaPlayer.OnInfoListener 1971 */ 1972 public static final int MEDIA_INFO_METADATA_UPDATE = 802; 1973 1974 /** 1975 * Interface definition of a callback to be invoked to communicate some 1976 * info and/or warning about the media or its playback. 1977 */ 1978 public interface OnInfoListener 1979 { 1980 /** 1981 * Called to indicate an info or a warning. 1982 * 1983 * @param mp the MediaPlayer the info pertains to. 1984 * @param what the type of info or warning. 1985 * <ul> 1986 * <li>{@link #MEDIA_INFO_UNKNOWN} 1987 * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING} 1988 * <li>{@link #MEDIA_INFO_BUFFERING_START} 1989 * <li>{@link #MEDIA_INFO_BUFFERING_END} 1990 * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING} 1991 * <li>{@link #MEDIA_INFO_NOT_SEEKABLE} 1992 * <li>{@link #MEDIA_INFO_METADATA_UPDATE} 1993 * </ul> 1994 * @param extra an extra code, specific to the info. Typically 1995 * implementation dependant. 1996 * @return True if the method handled the info, false if it didn't. 1997 * Returning false, or not having an OnErrorListener at all, will 1998 * cause the info to be discarded. 1999 */ 2000 boolean onInfo(MediaPlayer mp, int what, int extra); 2001 } 2002 2003 /** 2004 * Register a callback to be invoked when an info/warning is available. 2005 * 2006 * @param listener the callback that will be run 2007 */ 2008 public void setOnInfoListener(OnInfoListener listener) 2009 { 2010 mOnInfoListener = listener; 2011 } 2012 2013 private OnInfoListener mOnInfoListener; 2014 2015} 2016