MediaPlayer.java revision 467ec7eda8ad754d6a92d32040738b797ba5e994
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 * <p>When <code>path</code> refers to a local file, the file may actually be opened by a 818 * process other than the calling application. This implies that the pathname 819 * should be an absolute path (as any other process runs with unspecified current working 820 * directory), and that the pathname should reference a world-readable file. 821 * As an alternative, the application could first open the file for reading, 822 * and then use the file descriptor form {@link #setDataSource(FileDescriptor)}. 823 */ 824 public native void setDataSource(String path) 825 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException; 826 827 /** 828 * Sets the data source (file-path or http/rtsp URL) to use. 829 * 830 * @param path the path of the file, or the http/rtsp URL of the stream you want to play 831 * @param headers the headers associated with the http request for the stream you want to play 832 * @throws IllegalStateException if it is called in an invalid state 833 * @hide pending API council 834 */ 835 public void setDataSource(String path, Map<String, String> headers) 836 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException 837 { 838 String[] keys = null; 839 String[] values = null; 840 841 if (headers != null) { 842 keys = new String[headers.size()]; 843 values = new String[headers.size()]; 844 845 int i = 0; 846 for (Map.Entry<String, String> entry: headers.entrySet()) { 847 keys[i] = entry.getKey(); 848 values[i] = entry.getValue(); 849 ++i; 850 } 851 } 852 _setDataSource(path, keys, values); 853 } 854 855 private native void _setDataSource( 856 String path, String[] keys, String[] values) 857 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException; 858 859 /** 860 * Sets the data source (FileDescriptor) to use. It is the caller's responsibility 861 * to close the file descriptor. It is safe to do so as soon as this call returns. 862 * 863 * @param fd the FileDescriptor for the file you want to play 864 * @throws IllegalStateException if it is called in an invalid state 865 */ 866 public void setDataSource(FileDescriptor fd) 867 throws IOException, IllegalArgumentException, IllegalStateException { 868 // intentionally less than LONG_MAX 869 setDataSource(fd, 0, 0x7ffffffffffffffL); 870 } 871 872 /** 873 * Sets the data source (FileDescriptor) to use. The FileDescriptor must be 874 * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility 875 * to close the file descriptor. It is safe to do so as soon as this call returns. 876 * 877 * @param fd the FileDescriptor for the file you want to play 878 * @param offset the offset into the file where the data to be played starts, in bytes 879 * @param length the length in bytes of the data to be played 880 * @throws IllegalStateException if it is called in an invalid state 881 */ 882 public native void setDataSource(FileDescriptor fd, long offset, long length) 883 throws IOException, IllegalArgumentException, IllegalStateException; 884 885 /** 886 * Prepares the player for playback, synchronously. 887 * 888 * After setting the datasource and the display surface, you need to either 889 * call prepare() or prepareAsync(). For files, it is OK to call prepare(), 890 * which blocks until MediaPlayer is ready for playback. 891 * 892 * @throws IllegalStateException if it is called in an invalid state 893 */ 894 public native void prepare() throws IOException, IllegalStateException; 895 896 /** 897 * Prepares the player for playback, asynchronously. 898 * 899 * After setting the datasource and the display surface, you need to either 900 * call prepare() or prepareAsync(). For streams, you should call prepareAsync(), 901 * which returns immediately, rather than blocking until enough data has been 902 * buffered. 903 * 904 * @throws IllegalStateException if it is called in an invalid state 905 */ 906 public native void prepareAsync() throws IllegalStateException; 907 908 /** 909 * Starts or resumes playback. If playback had previously been paused, 910 * playback will continue from where it was paused. If playback had 911 * been stopped, or never started before, playback will start at the 912 * beginning. 913 * 914 * @throws IllegalStateException if it is called in an invalid state 915 */ 916 public void start() throws IllegalStateException { 917 stayAwake(true); 918 _start(); 919 } 920 921 private native void _start() throws IllegalStateException; 922 923 /** 924 * Stops playback after playback has been stopped or paused. 925 * 926 * @throws IllegalStateException if the internal player engine has not been 927 * initialized. 928 */ 929 public void stop() throws IllegalStateException { 930 stayAwake(false); 931 _stop(); 932 } 933 934 private native void _stop() throws IllegalStateException; 935 936 /** 937 * Pauses playback. Call start() to resume. 938 * 939 * @throws IllegalStateException if the internal player engine has not been 940 * initialized. 941 */ 942 public void pause() throws IllegalStateException { 943 stayAwake(false); 944 _pause(); 945 } 946 947 private native void _pause() throws IllegalStateException; 948 949 /** 950 * Set the low-level power management behavior for this MediaPlayer. This 951 * can be used when the MediaPlayer is not playing through a SurfaceHolder 952 * set with {@link #setDisplay(SurfaceHolder)} and thus can use the 953 * high-level {@link #setScreenOnWhilePlaying(boolean)} feature. 954 * 955 * <p>This function has the MediaPlayer access the low-level power manager 956 * service to control the device's power usage while playing is occurring. 957 * The parameter is a combination of {@link android.os.PowerManager} wake flags. 958 * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK} 959 * permission. 960 * By default, no attempt is made to keep the device awake during playback. 961 * 962 * @param context the Context to use 963 * @param mode the power/wake mode to set 964 * @see android.os.PowerManager 965 */ 966 public void setWakeMode(Context context, int mode) { 967 boolean washeld = false; 968 if (mWakeLock != null) { 969 if (mWakeLock.isHeld()) { 970 washeld = true; 971 mWakeLock.release(); 972 } 973 mWakeLock = null; 974 } 975 976 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 977 mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName()); 978 mWakeLock.setReferenceCounted(false); 979 if (washeld) { 980 mWakeLock.acquire(); 981 } 982 } 983 984 /** 985 * Control whether we should use the attached SurfaceHolder to keep the 986 * screen on while video playback is occurring. This is the preferred 987 * method over {@link #setWakeMode} where possible, since it doesn't 988 * require that the application have permission for low-level wake lock 989 * access. 990 * 991 * @param screenOn Supply true to keep the screen on, false to allow it 992 * to turn off. 993 */ 994 public void setScreenOnWhilePlaying(boolean screenOn) { 995 if (mScreenOnWhilePlaying != screenOn) { 996 if (screenOn && mSurfaceHolder == null) { 997 Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder"); 998 } 999 mScreenOnWhilePlaying = screenOn; 1000 updateSurfaceScreenOn(); 1001 } 1002 } 1003 1004 private void stayAwake(boolean awake) { 1005 if (mWakeLock != null) { 1006 if (awake && !mWakeLock.isHeld()) { 1007 mWakeLock.acquire(); 1008 } else if (!awake && mWakeLock.isHeld()) { 1009 mWakeLock.release(); 1010 } 1011 } 1012 mStayAwake = awake; 1013 updateSurfaceScreenOn(); 1014 } 1015 1016 private void updateSurfaceScreenOn() { 1017 if (mSurfaceHolder != null) { 1018 mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake); 1019 } 1020 } 1021 1022 /** 1023 * Returns the width of the video. 1024 * 1025 * @return the width of the video, or 0 if there is no video, 1026 * no display surface was set, or the width has not been determined 1027 * yet. The OnVideoSizeChangedListener can be registered via 1028 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)} 1029 * to provide a notification when the width is available. 1030 */ 1031 public native int getVideoWidth(); 1032 1033 /** 1034 * Returns the height of the video. 1035 * 1036 * @return the height of the video, or 0 if there is no video, 1037 * no display surface was set, or the height has not been determined 1038 * yet. The OnVideoSizeChangedListener can be registered via 1039 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)} 1040 * to provide a notification when the height is available. 1041 */ 1042 public native int getVideoHeight(); 1043 1044 /** 1045 * Checks whether the MediaPlayer is playing. 1046 * 1047 * @return true if currently playing, false otherwise 1048 */ 1049 public native boolean isPlaying(); 1050 1051 /** 1052 * Seeks to specified time position. 1053 * 1054 * @param msec the offset in milliseconds from the start to seek to 1055 * @throws IllegalStateException if the internal player engine has not been 1056 * initialized 1057 */ 1058 public native void seekTo(int msec) throws IllegalStateException; 1059 1060 /** 1061 * Gets the current playback position. 1062 * 1063 * @return the current position in milliseconds 1064 */ 1065 public native int getCurrentPosition(); 1066 1067 /** 1068 * Gets the duration of the file. 1069 * 1070 * @return the duration in milliseconds 1071 */ 1072 public native int getDuration(); 1073 1074 /** 1075 * Gets the media metadata. 1076 * 1077 * @param update_only controls whether the full set of available 1078 * metadata is returned or just the set that changed since the 1079 * last call. See {@see #METADATA_UPDATE_ONLY} and {@see 1080 * #METADATA_ALL}. 1081 * 1082 * @param apply_filter if true only metadata that matches the 1083 * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see 1084 * #BYPASS_METADATA_FILTER}. 1085 * 1086 * @return The metadata, possibly empty. null if an error occured. 1087 // FIXME: unhide. 1088 * {@hide} 1089 */ 1090 public Metadata getMetadata(final boolean update_only, 1091 final boolean apply_filter) { 1092 Parcel reply = Parcel.obtain(); 1093 Metadata data = new Metadata(); 1094 1095 if (!native_getMetadata(update_only, apply_filter, reply)) { 1096 reply.recycle(); 1097 return null; 1098 } 1099 1100 // Metadata takes over the parcel, don't recycle it unless 1101 // there is an error. 1102 if (!data.parse(reply)) { 1103 reply.recycle(); 1104 return null; 1105 } 1106 return data; 1107 } 1108 1109 /** 1110 * Set a filter for the metadata update notification and update 1111 * retrieval. The caller provides 2 set of metadata keys, allowed 1112 * and blocked. The blocked set always takes precedence over the 1113 * allowed one. 1114 * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as 1115 * shorthands to allow/block all or no metadata. 1116 * 1117 * By default, there is no filter set. 1118 * 1119 * @param allow Is the set of metadata the client is interested 1120 * in receiving new notifications for. 1121 * @param block Is the set of metadata the client is not interested 1122 * in receiving new notifications for. 1123 * @return The call status code. 1124 * 1125 // FIXME: unhide. 1126 * {@hide} 1127 */ 1128 public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) { 1129 // Do our serialization manually instead of calling 1130 // Parcel.writeArray since the sets are made of the same type 1131 // we avoid paying the price of calling writeValue (used by 1132 // writeArray) which burns an extra int per element to encode 1133 // the type. 1134 Parcel request = newRequest(); 1135 1136 // The parcel starts already with an interface token. There 1137 // are 2 filters. Each one starts with a 4bytes number to 1138 // store the len followed by a number of int (4 bytes as well) 1139 // representing the metadata type. 1140 int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size()); 1141 1142 if (request.dataCapacity() < capacity) { 1143 request.setDataCapacity(capacity); 1144 } 1145 1146 request.writeInt(allow.size()); 1147 for(Integer t: allow) { 1148 request.writeInt(t); 1149 } 1150 request.writeInt(block.size()); 1151 for(Integer t: block) { 1152 request.writeInt(t); 1153 } 1154 return native_setMetadataFilter(request); 1155 } 1156 1157 /** 1158 * Set the MediaPlayer to start when this MediaPlayer finishes playback 1159 * (i.e. reaches the end of the stream). 1160 * The media framework will attempt to transition from this player to 1161 * the next as seamlessly as possible. The next player can be set at 1162 * any time before completion. The next player must be prepared by the 1163 * app, and the application should not call start() on it. 1164 * The next MediaPlayer must be different from 'this'. An exception 1165 * will be thrown if next == this. 1166 * The application may call setNextMediaPlayer(null) to indicate no 1167 * next player should be started at the end of playback. 1168 * If the current player is looping, it will keep looping and the next 1169 * player will not be started. 1170 * 1171 * @param next the player to start after this one completes playback. 1172 * 1173 */ 1174 public native void setNextMediaPlayer(MediaPlayer next); 1175 1176 /** 1177 * Releases resources associated with this MediaPlayer object. 1178 * It is considered good practice to call this method when you're 1179 * done using the MediaPlayer. In particular, whenever an Activity 1180 * of an application is paused (its onPause() method is called), 1181 * or stopped (its onStop() method is called), this method should be 1182 * invoked to release the MediaPlayer object, unless the application 1183 * has a special need to keep the object around. In addition to 1184 * unnecessary resources (such as memory and instances of codecs) 1185 * being held, failure to call this method immediately if a 1186 * MediaPlayer object is no longer needed may also lead to 1187 * continuous battery consumption for mobile devices, and playback 1188 * failure for other applications if no multiple instances of the 1189 * same codec are supported on a device. Even if multiple instances 1190 * of the same codec are supported, some performance degradation 1191 * may be expected when unnecessary multiple instances are used 1192 * at the same time. 1193 */ 1194 public void release() { 1195 stayAwake(false); 1196 updateSurfaceScreenOn(); 1197 mOnPreparedListener = null; 1198 mOnBufferingUpdateListener = null; 1199 mOnCompletionListener = null; 1200 mOnSeekCompleteListener = null; 1201 mOnErrorListener = null; 1202 mOnInfoListener = null; 1203 mOnVideoSizeChangedListener = null; 1204 mOnTimedTextListener = null; 1205 _release(); 1206 } 1207 1208 private native void _release(); 1209 1210 /** 1211 * Resets the MediaPlayer to its uninitialized state. After calling 1212 * this method, you will have to initialize it again by setting the 1213 * data source and calling prepare(). 1214 */ 1215 public void reset() { 1216 stayAwake(false); 1217 _reset(); 1218 // make sure none of the listeners get called anymore 1219 mEventHandler.removeCallbacksAndMessages(null); 1220 } 1221 1222 private native void _reset(); 1223 1224 /** 1225 * Sets the audio stream type for this MediaPlayer. See {@link AudioManager} 1226 * for a list of stream types. Must call this method before prepare() or 1227 * prepareAsync() in order for the target stream type to become effective 1228 * thereafter. 1229 * 1230 * @param streamtype the audio stream type 1231 * @see android.media.AudioManager 1232 */ 1233 public native void setAudioStreamType(int streamtype); 1234 1235 /** 1236 * Sets the player to be looping or non-looping. 1237 * 1238 * @param looping whether to loop or not 1239 */ 1240 public native void setLooping(boolean looping); 1241 1242 /** 1243 * Checks whether the MediaPlayer is looping or non-looping. 1244 * 1245 * @return true if the MediaPlayer is currently looping, false otherwise 1246 */ 1247 public native boolean isLooping(); 1248 1249 /** 1250 * Sets the volume on this player. 1251 * This API is recommended for balancing the output of audio streams 1252 * within an application. Unless you are writing an application to 1253 * control user settings, this API should be used in preference to 1254 * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of 1255 * a particular type. Note that the passed volume values are raw scalars. 1256 * UI controls should be scaled logarithmically. 1257 * 1258 * @param leftVolume left volume scalar 1259 * @param rightVolume right volume scalar 1260 */ 1261 public native void setVolume(float leftVolume, float rightVolume); 1262 1263 /** 1264 * Currently not implemented, returns null. 1265 * @deprecated 1266 * @hide 1267 */ 1268 public native Bitmap getFrameAt(int msec) throws IllegalStateException; 1269 1270 /** 1271 * Sets the audio session ID. 1272 * 1273 * @param sessionId the audio session ID. 1274 * The audio session ID is a system wide unique identifier for the audio stream played by 1275 * this MediaPlayer instance. 1276 * The primary use of the audio session ID is to associate audio effects to a particular 1277 * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect, 1278 * this effect will be applied only to the audio content of media players within the same 1279 * audio session and not to the output mix. 1280 * When created, a MediaPlayer instance automatically generates its own audio session ID. 1281 * However, it is possible to force this player to be part of an already existing audio session 1282 * by calling this method. 1283 * This method must be called before one of the overloaded <code> setDataSource </code> methods. 1284 * @throws IllegalStateException if it is called in an invalid state 1285 */ 1286 public native void setAudioSessionId(int sessionId) throws IllegalArgumentException, IllegalStateException; 1287 1288 /** 1289 * Returns the audio session ID. 1290 * 1291 * @return the audio session ID. {@see #setAudioSessionId(int)} 1292 * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed. 1293 */ 1294 public native int getAudioSessionId(); 1295 1296 /** 1297 * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation 1298 * effect which can be applied on any sound source that directs a certain amount of its 1299 * energy to this effect. This amount is defined by setAuxEffectSendLevel(). 1300 * {@see #setAuxEffectSendLevel(float)}. 1301 * <p>After creating an auxiliary effect (e.g. 1302 * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with 1303 * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method 1304 * to attach the player to the effect. 1305 * <p>To detach the effect from the player, call this method with a null effect id. 1306 * <p>This method must be called after one of the overloaded <code> setDataSource </code> 1307 * methods. 1308 * @param effectId system wide unique id of the effect to attach 1309 */ 1310 public native void attachAuxEffect(int effectId); 1311 1312 /* Do not change these values (starting with KEY_PARAMETER) without updating 1313 * their counterparts in include/media/mediaplayer.h! 1314 */ 1315 /* 1316 * Key used in setParameter method. 1317 * Indicates the index of the timed text track to be enabled/disabled. 1318 * The index includes both the in-band and out-of-band timed text. 1319 * The index should start from in-band text if any. Application can retrieve the number 1320 * of in-band text tracks by using MediaMetadataRetriever::extractMetadata(). 1321 * Note it might take a few hundred ms to scan an out-of-band text file 1322 * before displaying it. 1323 */ 1324 private static final int KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX = 1000; 1325 /* 1326 * Key used in setParameter method. 1327 * Used to add out-of-band timed text source path. 1328 * Application can add multiple text sources by calling setParameter() with 1329 * KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE multiple times. 1330 */ 1331 private static final int KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE = 1001; 1332 1333 // There are currently no defined keys usable from Java with get*Parameter. 1334 // But if any keys are defined, the order must be kept in sync with include/media/mediaplayer.h. 1335 // private static final int KEY_PARAMETER_... = ...; 1336 1337 /** 1338 * Sets the parameter indicated by key. 1339 * @param key key indicates the parameter to be set. 1340 * @param value value of the parameter to be set. 1341 * @return true if the parameter is set successfully, false otherwise 1342 * {@hide} 1343 */ 1344 public native boolean setParameter(int key, Parcel value); 1345 1346 /** 1347 * Sets the parameter indicated by key. 1348 * @param key key indicates the parameter to be set. 1349 * @param value value of the parameter to be set. 1350 * @return true if the parameter is set successfully, false otherwise 1351 * {@hide} 1352 */ 1353 public boolean setParameter(int key, String value) { 1354 Parcel p = Parcel.obtain(); 1355 p.writeString(value); 1356 boolean ret = setParameter(key, p); 1357 p.recycle(); 1358 return ret; 1359 } 1360 1361 /** 1362 * Sets the parameter indicated by key. 1363 * @param key key indicates the parameter to be set. 1364 * @param value value of the parameter to be set. 1365 * @return true if the parameter is set successfully, false otherwise 1366 * {@hide} 1367 */ 1368 public boolean setParameter(int key, int value) { 1369 Parcel p = Parcel.obtain(); 1370 p.writeInt(value); 1371 boolean ret = setParameter(key, p); 1372 p.recycle(); 1373 return ret; 1374 } 1375 1376 /** 1377 * Gets the value of the parameter indicated by key. 1378 * @param key key indicates the parameter to get. 1379 * @param reply value of the parameter to get. 1380 */ 1381 private native void getParameter(int key, Parcel reply); 1382 1383 /** 1384 * Gets the value of the parameter indicated by key. 1385 * The caller is responsible for recycling the returned parcel. 1386 * @param key key indicates the parameter to get. 1387 * @return value of the parameter. 1388 * {@hide} 1389 */ 1390 public Parcel getParcelParameter(int key) { 1391 Parcel p = Parcel.obtain(); 1392 getParameter(key, p); 1393 return p; 1394 } 1395 1396 /** 1397 * Gets the value of the parameter indicated by key. 1398 * @param key key indicates the parameter to get. 1399 * @return value of the parameter. 1400 * {@hide} 1401 */ 1402 public String getStringParameter(int key) { 1403 Parcel p = Parcel.obtain(); 1404 getParameter(key, p); 1405 String ret = p.readString(); 1406 p.recycle(); 1407 return ret; 1408 } 1409 1410 /** 1411 * Gets the value of the parameter indicated by key. 1412 * @param key key indicates the parameter to get. 1413 * @return value of the parameter. 1414 * {@hide} 1415 */ 1416 public int getIntParameter(int key) { 1417 Parcel p = Parcel.obtain(); 1418 getParameter(key, p); 1419 int ret = p.readInt(); 1420 p.recycle(); 1421 return ret; 1422 } 1423 1424 /** 1425 * Sets the send level of the player to the attached auxiliary effect 1426 * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0. 1427 * <p>By default the send level is 0, so even if an effect is attached to the player 1428 * this method must be called for the effect to be applied. 1429 * <p>Note that the passed level value is a raw scalar. UI controls should be scaled 1430 * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB, 1431 * so an appropriate conversion from linear UI input x to level is: 1432 * x == 0 -> level = 0 1433 * 0 < x <= R -> level = 10^(72*(x-R)/20/R) 1434 * @param level send level scalar 1435 */ 1436 public native void setAuxEffectSendLevel(float level); 1437 1438 /** 1439 * @param request Parcel destinated to the media player. The 1440 * Interface token must be set to the IMediaPlayer 1441 * one to be routed correctly through the system. 1442 * @param reply[out] Parcel that will contain the reply. 1443 * @return The status code. 1444 */ 1445 private native final int native_invoke(Parcel request, Parcel reply); 1446 1447 1448 /** 1449 * @param update_only If true fetch only the set of metadata that have 1450 * changed since the last invocation of getMetadata. 1451 * The set is built using the unfiltered 1452 * notifications the native player sent to the 1453 * MediaPlayerService during that period of 1454 * time. If false, all the metadatas are considered. 1455 * @param apply_filter If true, once the metadata set has been built based on 1456 * the value update_only, the current filter is applied. 1457 * @param reply[out] On return contains the serialized 1458 * metadata. Valid only if the call was successful. 1459 * @return The status code. 1460 */ 1461 private native final boolean native_getMetadata(boolean update_only, 1462 boolean apply_filter, 1463 Parcel reply); 1464 1465 /** 1466 * @param request Parcel with the 2 serialized lists of allowed 1467 * metadata types followed by the one to be 1468 * dropped. Each list starts with an integer 1469 * indicating the number of metadata type elements. 1470 * @return The status code. 1471 */ 1472 private native final int native_setMetadataFilter(Parcel request); 1473 1474 private static native final void native_init(); 1475 private native final void native_setup(Object mediaplayer_this); 1476 private native final void native_finalize(); 1477 1478 /** 1479 * @param index The index of the text track to be turned on. 1480 * @return true if the text track is enabled successfully. 1481 * {@hide} 1482 */ 1483 public boolean enableTimedTextTrackIndex(int index) { 1484 if (index < 0) { 1485 return false; 1486 } 1487 return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, index); 1488 } 1489 1490 /** 1491 * Enables the first timed text track if any. 1492 * @return true if the text track is enabled successfully 1493 * {@hide} 1494 */ 1495 public boolean enableTimedText() { 1496 return enableTimedTextTrackIndex(0); 1497 } 1498 1499 /** 1500 * Disables timed text display. 1501 * @return true if the text track is disabled successfully. 1502 * {@hide} 1503 */ 1504 public boolean disableTimedText() { 1505 return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, -1); 1506 } 1507 1508 /** 1509 * @param reply Parcel with audio/video duration info for battery 1510 tracking usage 1511 * @return The status code. 1512 * {@hide} 1513 */ 1514 public native static int native_pullBatteryData(Parcel reply); 1515 1516 /** 1517 * Sets the target UDP re-transmit endpoint for the low level player. 1518 * Generally, the address portion of the endpoint is an IP multicast 1519 * address, although a unicast address would be equally valid. When a valid 1520 * retransmit endpoint has been set, the media player will not decode and 1521 * render the media presentation locally. Instead, the player will attempt 1522 * to re-multiplex its media data using the Android@Home RTP profile and 1523 * re-transmit to the target endpoint. Receiver devices (which may be 1524 * either the same as the transmitting device or different devices) may 1525 * instantiate, prepare, and start a receiver player using a setDataSource 1526 * URL of the form... 1527 * 1528 * aahRX://<multicastIP>:<port> 1529 * 1530 * to receive, decode and render the re-transmitted content. 1531 * 1532 * setRetransmitEndpoint may only be called before setDataSource has been 1533 * called; while the player is in the Idle state. 1534 * 1535 * @param endpoint the address and UDP port of the re-transmission target or 1536 * null if no re-transmission is to be performed. 1537 * @throws IllegalStateException if it is called in an invalid state 1538 * @throws IllegalArgumentException if the retransmit endpoint is supplied, 1539 * but invalid. 1540 * 1541 * {@hide} pending API council 1542 */ 1543 public void setRetransmitEndpoint(InetSocketAddress endpoint) 1544 throws IllegalStateException, IllegalArgumentException 1545 { 1546 String addrString = null; 1547 int port = 0; 1548 1549 if (null != endpoint) { 1550 addrString = endpoint.getAddress().getHostAddress(); 1551 port = endpoint.getPort(); 1552 } 1553 1554 int ret = native_setRetransmitEndpoint(addrString, port); 1555 if (ret != 0) { 1556 throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret); 1557 } 1558 } 1559 1560 private native final int native_setRetransmitEndpoint(String addrString, int port); 1561 1562 @Override 1563 protected void finalize() { native_finalize(); } 1564 1565 /* Do not change these values without updating their counterparts 1566 * in include/media/mediaplayer.h! 1567 */ 1568 private static final int MEDIA_NOP = 0; // interface test message 1569 private static final int MEDIA_PREPARED = 1; 1570 private static final int MEDIA_PLAYBACK_COMPLETE = 2; 1571 private static final int MEDIA_BUFFERING_UPDATE = 3; 1572 private static final int MEDIA_SEEK_COMPLETE = 4; 1573 private static final int MEDIA_SET_VIDEO_SIZE = 5; 1574 private static final int MEDIA_TIMED_TEXT = 99; 1575 private static final int MEDIA_ERROR = 100; 1576 private static final int MEDIA_INFO = 200; 1577 1578 private class EventHandler extends Handler 1579 { 1580 private MediaPlayer mMediaPlayer; 1581 1582 public EventHandler(MediaPlayer mp, Looper looper) { 1583 super(looper); 1584 mMediaPlayer = mp; 1585 } 1586 1587 @Override 1588 public void handleMessage(Message msg) { 1589 if (mMediaPlayer.mNativeContext == 0) { 1590 Log.w(TAG, "mediaplayer went away with unhandled events"); 1591 return; 1592 } 1593 switch(msg.what) { 1594 case MEDIA_PREPARED: 1595 if (mOnPreparedListener != null) 1596 mOnPreparedListener.onPrepared(mMediaPlayer); 1597 return; 1598 1599 case MEDIA_PLAYBACK_COMPLETE: 1600 if (mOnCompletionListener != null) 1601 mOnCompletionListener.onCompletion(mMediaPlayer); 1602 stayAwake(false); 1603 return; 1604 1605 case MEDIA_BUFFERING_UPDATE: 1606 if (mOnBufferingUpdateListener != null) 1607 mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1); 1608 return; 1609 1610 case MEDIA_SEEK_COMPLETE: 1611 if (mOnSeekCompleteListener != null) 1612 mOnSeekCompleteListener.onSeekComplete(mMediaPlayer); 1613 return; 1614 1615 case MEDIA_SET_VIDEO_SIZE: 1616 if (mOnVideoSizeChangedListener != null) 1617 mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2); 1618 return; 1619 1620 case MEDIA_ERROR: 1621 // For PV specific error values (msg.arg2) look in 1622 // opencore/pvmi/pvmf/include/pvmf_return_codes.h 1623 Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")"); 1624 boolean error_was_handled = false; 1625 if (mOnErrorListener != null) { 1626 error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2); 1627 } 1628 if (mOnCompletionListener != null && ! error_was_handled) { 1629 mOnCompletionListener.onCompletion(mMediaPlayer); 1630 } 1631 stayAwake(false); 1632 return; 1633 1634 case MEDIA_INFO: 1635 if (msg.arg1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) { 1636 Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")"); 1637 } 1638 if (mOnInfoListener != null) { 1639 mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2); 1640 } 1641 // No real default action so far. 1642 return; 1643 case MEDIA_TIMED_TEXT: 1644 if (mOnTimedTextListener != null) { 1645 if (msg.obj == null) { 1646 mOnTimedTextListener.onTimedText(mMediaPlayer, null); 1647 } else { 1648 if (msg.obj instanceof byte[]) { 1649 TimedText text = new TimedText((byte[])(msg.obj)); 1650 mOnTimedTextListener.onTimedText(mMediaPlayer, text); 1651 } 1652 } 1653 } 1654 return; 1655 1656 case MEDIA_NOP: // interface test message - ignore 1657 break; 1658 1659 default: 1660 Log.e(TAG, "Unknown message type " + msg.what); 1661 return; 1662 } 1663 } 1664 } 1665 1666 /** 1667 * Called from native code when an interesting event happens. This method 1668 * just uses the EventHandler system to post the event back to the main app thread. 1669 * We use a weak reference to the original MediaPlayer object so that the native 1670 * code is safe from the object disappearing from underneath it. (This is 1671 * the cookie passed to native_setup().) 1672 */ 1673 private static void postEventFromNative(Object mediaplayer_ref, 1674 int what, int arg1, int arg2, Object obj) 1675 { 1676 MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get(); 1677 if (mp == null) { 1678 return; 1679 } 1680 1681 if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) { 1682 // this acquires the wakelock if needed, and sets the client side state 1683 mp.start(); 1684 } 1685 if (mp.mEventHandler != null) { 1686 Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj); 1687 mp.mEventHandler.sendMessage(m); 1688 } 1689 } 1690 1691 /** 1692 * Interface definition for a callback to be invoked when the media 1693 * source is ready for playback. 1694 */ 1695 public interface OnPreparedListener 1696 { 1697 /** 1698 * Called when the media file is ready for playback. 1699 * 1700 * @param mp the MediaPlayer that is ready for playback 1701 */ 1702 void onPrepared(MediaPlayer mp); 1703 } 1704 1705 /** 1706 * Register a callback to be invoked when the media source is ready 1707 * for playback. 1708 * 1709 * @param listener the callback that will be run 1710 */ 1711 public void setOnPreparedListener(OnPreparedListener listener) 1712 { 1713 mOnPreparedListener = listener; 1714 } 1715 1716 private OnPreparedListener mOnPreparedListener; 1717 1718 /** 1719 * Interface definition for a callback to be invoked when playback of 1720 * a media source has completed. 1721 */ 1722 public interface OnCompletionListener 1723 { 1724 /** 1725 * Called when the end of a media source is reached during playback. 1726 * 1727 * @param mp the MediaPlayer that reached the end of the file 1728 */ 1729 void onCompletion(MediaPlayer mp); 1730 } 1731 1732 /** 1733 * Register a callback to be invoked when the end of a media source 1734 * has been reached during playback. 1735 * 1736 * @param listener the callback that will be run 1737 */ 1738 public void setOnCompletionListener(OnCompletionListener listener) 1739 { 1740 mOnCompletionListener = listener; 1741 } 1742 1743 private OnCompletionListener mOnCompletionListener; 1744 1745 /** 1746 * Interface definition of a callback to be invoked indicating buffering 1747 * status of a media resource being streamed over the network. 1748 */ 1749 public interface OnBufferingUpdateListener 1750 { 1751 /** 1752 * Called to update status in buffering a media stream received through 1753 * progressive HTTP download. The received buffering percentage 1754 * indicates how much of the content has been buffered or played. 1755 * For example a buffering update of 80 percent when half the content 1756 * has already been played indicates that the next 30 percent of the 1757 * content to play has been buffered. 1758 * 1759 * @param mp the MediaPlayer the update pertains to 1760 * @param percent the percentage (0-100) of the content 1761 * that has been buffered or played thus far 1762 */ 1763 void onBufferingUpdate(MediaPlayer mp, int percent); 1764 } 1765 1766 /** 1767 * Register a callback to be invoked when the status of a network 1768 * stream's buffer has changed. 1769 * 1770 * @param listener the callback that will be run. 1771 */ 1772 public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener) 1773 { 1774 mOnBufferingUpdateListener = listener; 1775 } 1776 1777 private OnBufferingUpdateListener mOnBufferingUpdateListener; 1778 1779 /** 1780 * Interface definition of a callback to be invoked indicating 1781 * the completion of a seek operation. 1782 */ 1783 public interface OnSeekCompleteListener 1784 { 1785 /** 1786 * Called to indicate the completion of a seek operation. 1787 * 1788 * @param mp the MediaPlayer that issued the seek operation 1789 */ 1790 public void onSeekComplete(MediaPlayer mp); 1791 } 1792 1793 /** 1794 * Register a callback to be invoked when a seek operation has been 1795 * completed. 1796 * 1797 * @param listener the callback that will be run 1798 */ 1799 public void setOnSeekCompleteListener(OnSeekCompleteListener listener) 1800 { 1801 mOnSeekCompleteListener = listener; 1802 } 1803 1804 private OnSeekCompleteListener mOnSeekCompleteListener; 1805 1806 /** 1807 * Interface definition of a callback to be invoked when the 1808 * video size is first known or updated 1809 */ 1810 public interface OnVideoSizeChangedListener 1811 { 1812 /** 1813 * Called to indicate the video size 1814 * 1815 * The video size (width and height) could be 0 if there was no video, 1816 * no display surface was set, or the value was not determined yet. 1817 * 1818 * @param mp the MediaPlayer associated with this callback 1819 * @param width the width of the video 1820 * @param height the height of the video 1821 */ 1822 public void onVideoSizeChanged(MediaPlayer mp, int width, int height); 1823 } 1824 1825 /** 1826 * Register a callback to be invoked when the video size is 1827 * known or updated. 1828 * 1829 * @param listener the callback that will be run 1830 */ 1831 public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener) 1832 { 1833 mOnVideoSizeChangedListener = listener; 1834 } 1835 1836 private OnVideoSizeChangedListener mOnVideoSizeChangedListener; 1837 1838 /** 1839 * Interface definition of a callback to be invoked when a 1840 * timed text is available for display. 1841 * {@hide} 1842 */ 1843 public interface OnTimedTextListener 1844 { 1845 /** 1846 * Called to indicate an avaliable timed text 1847 * 1848 * @param mp the MediaPlayer associated with this callback 1849 * @param text the timed text sample which contains the text 1850 * needed to be displayed and the display format. 1851 * {@hide} 1852 */ 1853 public void onTimedText(MediaPlayer mp, TimedText text); 1854 } 1855 1856 /** 1857 * Register a callback to be invoked when a timed text is available 1858 * for display. 1859 * 1860 * @param listener the callback that will be run 1861 * {@hide} 1862 */ 1863 public void setOnTimedTextListener(OnTimedTextListener listener) 1864 { 1865 mOnTimedTextListener = listener; 1866 } 1867 1868 private OnTimedTextListener mOnTimedTextListener; 1869 1870 1871 /* Do not change these values without updating their counterparts 1872 * in include/media/mediaplayer.h! 1873 */ 1874 /** Unspecified media player error. 1875 * @see android.media.MediaPlayer.OnErrorListener 1876 */ 1877 public static final int MEDIA_ERROR_UNKNOWN = 1; 1878 1879 /** Media server died. In this case, the application must release the 1880 * MediaPlayer object and instantiate a new one. 1881 * @see android.media.MediaPlayer.OnErrorListener 1882 */ 1883 public static final int MEDIA_ERROR_SERVER_DIED = 100; 1884 1885 /** The video is streamed and its container is not valid for progressive 1886 * playback i.e the video's index (e.g moov atom) is not at the start of the 1887 * file. 1888 * @see android.media.MediaPlayer.OnErrorListener 1889 */ 1890 public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200; 1891 1892 /** 1893 * Interface definition of a callback to be invoked when there 1894 * has been an error during an asynchronous operation (other errors 1895 * will throw exceptions at method call time). 1896 */ 1897 public interface OnErrorListener 1898 { 1899 /** 1900 * Called to indicate an error. 1901 * 1902 * @param mp the MediaPlayer the error pertains to 1903 * @param what the type of error that has occurred: 1904 * <ul> 1905 * <li>{@link #MEDIA_ERROR_UNKNOWN} 1906 * <li>{@link #MEDIA_ERROR_SERVER_DIED} 1907 * </ul> 1908 * @param extra an extra code, specific to the error. Typically 1909 * implementation dependant. 1910 * @return True if the method handled the error, false if it didn't. 1911 * Returning false, or not having an OnErrorListener at all, will 1912 * cause the OnCompletionListener to be called. 1913 */ 1914 boolean onError(MediaPlayer mp, int what, int extra); 1915 } 1916 1917 /** 1918 * Register a callback to be invoked when an error has happened 1919 * during an asynchronous operation. 1920 * 1921 * @param listener the callback that will be run 1922 */ 1923 public void setOnErrorListener(OnErrorListener listener) 1924 { 1925 mOnErrorListener = listener; 1926 } 1927 1928 private OnErrorListener mOnErrorListener; 1929 1930 1931 /* Do not change these values without updating their counterparts 1932 * in include/media/mediaplayer.h! 1933 */ 1934 /** Unspecified media player info. 1935 * @see android.media.MediaPlayer.OnInfoListener 1936 */ 1937 public static final int MEDIA_INFO_UNKNOWN = 1; 1938 1939 /** The player was started because it was used as the next player for another 1940 * player, which just completed playback. 1941 * @see android.media.MediaPlayer.OnInfoListener 1942 * @hide 1943 */ 1944 public static final int MEDIA_INFO_STARTED_AS_NEXT = 2; 1945 1946 /** The video is too complex for the decoder: it can't decode frames fast 1947 * enough. Possibly only the audio plays fine at this stage. 1948 * @see android.media.MediaPlayer.OnInfoListener 1949 */ 1950 public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; 1951 1952 /** MediaPlayer is temporarily pausing playback internally in order to 1953 * buffer more data. 1954 * @see android.media.MediaPlayer.OnInfoListener 1955 */ 1956 public static final int MEDIA_INFO_BUFFERING_START = 701; 1957 1958 /** MediaPlayer is resuming playback after filling buffers. 1959 * @see android.media.MediaPlayer.OnInfoListener 1960 */ 1961 public static final int MEDIA_INFO_BUFFERING_END = 702; 1962 1963 /** Bad interleaving means that a media has been improperly interleaved or 1964 * not interleaved at all, e.g has all the video samples first then all the 1965 * audio ones. Video is playing but a lot of disk seeks may be happening. 1966 * @see android.media.MediaPlayer.OnInfoListener 1967 */ 1968 public static final int MEDIA_INFO_BAD_INTERLEAVING = 800; 1969 1970 /** The media cannot be seeked (e.g live stream) 1971 * @see android.media.MediaPlayer.OnInfoListener 1972 */ 1973 public static final int MEDIA_INFO_NOT_SEEKABLE = 801; 1974 1975 /** A new set of metadata is available. 1976 * @see android.media.MediaPlayer.OnInfoListener 1977 */ 1978 public static final int MEDIA_INFO_METADATA_UPDATE = 802; 1979 1980 /** 1981 * Interface definition of a callback to be invoked to communicate some 1982 * info and/or warning about the media or its playback. 1983 */ 1984 public interface OnInfoListener 1985 { 1986 /** 1987 * Called to indicate an info or a warning. 1988 * 1989 * @param mp the MediaPlayer the info pertains to. 1990 * @param what the type of info or warning. 1991 * <ul> 1992 * <li>{@link #MEDIA_INFO_UNKNOWN} 1993 * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING} 1994 * <li>{@link #MEDIA_INFO_BUFFERING_START} 1995 * <li>{@link #MEDIA_INFO_BUFFERING_END} 1996 * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING} 1997 * <li>{@link #MEDIA_INFO_NOT_SEEKABLE} 1998 * <li>{@link #MEDIA_INFO_METADATA_UPDATE} 1999 * </ul> 2000 * @param extra an extra code, specific to the info. Typically 2001 * implementation dependant. 2002 * @return True if the method handled the info, false if it didn't. 2003 * Returning false, or not having an OnErrorListener at all, will 2004 * cause the info to be discarded. 2005 */ 2006 boolean onInfo(MediaPlayer mp, int what, int extra); 2007 } 2008 2009 /** 2010 * Register a callback to be invoked when an info/warning is available. 2011 * 2012 * @param listener the callback that will be run 2013 */ 2014 public void setOnInfoListener(OnInfoListener listener) 2015 { 2016 mOnInfoListener = listener; 2017 } 2018 2019 private OnInfoListener mOnInfoListener; 2020 2021} 2022