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