SoundPool.java revision f992cbb9aae593c7787ac9c5f6b475e7bb0a92c5
1/* 2 * Copyright (C) 2007 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.util.AndroidRuntimeException; 20import android.util.Log; 21import java.io.File; 22import java.io.FileDescriptor; 23import android.os.ParcelFileDescriptor; 24import java.lang.ref.WeakReference; 25import android.content.Context; 26import android.content.res.AssetFileDescriptor; 27import java.io.IOException; 28 29import android.os.Handler; 30import android.os.Looper; 31import android.os.Message; 32 33/** 34 * The SoundPool class manages and plays audio resources for applications. 35 * 36 * <p>A SoundPool is a collection of samples that can be loaded into memory 37 * from a resource inside the APK or from a file in the file system. The 38 * SoundPool library uses the MediaPlayer service to decode the audio 39 * into a raw 16-bit PCM mono or stereo stream. This allows applications 40 * to ship with compressed streams without having to suffer the CPU load 41 * and latency of decompressing during playback.</p> 42 * 43 * <p>In addition to low-latency playback, SoundPool can also manage the number 44 * of audio streams being rendered at once. When the SoundPool object is 45 * constructed, the maxStreams parameter sets the maximum number of streams 46 * that can be played at a time from this single SoundPool. SoundPool tracks 47 * the number of active streams. If the maximum number of streams is exceeded, 48 * SoundPool will automatically stop a previously playing stream based first 49 * on priority and then by age within that priority. Limiting the maximum 50 * number of streams helps to cap CPU loading and reducing the likelihood that 51 * audio mixing will impact visuals or UI performance.</p> 52 * 53 * <p>Sounds can be looped by setting a non-zero loop value. A value of -1 54 * causes the sound to loop forever. In this case, the application must 55 * explicitly call the stop() function to stop the sound. Any other non-zero 56 * value will cause the sound to repeat the specified number of times, e.g. 57 * a value of 3 causes the sound to play a total of 4 times.</p> 58 * 59 * <p>The playback rate can also be changed. A playback rate of 1.0 causes 60 * the sound to play at its original frequency (resampled, if necessary, 61 * to the hardware output frequency). A playback rate of 2.0 causes the 62 * sound to play at twice its original frequency, and a playback rate of 63 * 0.5 causes it to play at half its original frequency. The playback 64 * rate range is 0.5 to 2.0.</p> 65 * 66 * <p>Priority runs low to high, i.e. higher numbers are higher priority. 67 * Priority is used when a call to play() would cause the number of active 68 * streams to exceed the value established by the maxStreams parameter when 69 * the SoundPool was created. In this case, the stream allocator will stop 70 * the lowest priority stream. If there are multiple streams with the same 71 * low priority, it will choose the oldest stream to stop. In the case 72 * where the priority of the new stream is lower than all the active 73 * streams, the new sound will not play and the play() function will return 74 * a streamID of zero.</p> 75 * 76 * <p>Let's examine a typical use case: A game consists of several levels of 77 * play. For each level, there is a set of unique sounds that are used only 78 * by that level. In this case, the game logic should create a new SoundPool 79 * object when the first level is loaded. The level data itself might contain 80 * the list of sounds to be used by this level. The loading logic iterates 81 * through the list of sounds calling the appropriate SoundPool.load() 82 * function. This should typically be done early in the process to allow time 83 * for decompressing the audio to raw PCM format before they are needed for 84 * playback.</p> 85 * 86 * <p>Once the sounds are loaded and play has started, the application can 87 * trigger sounds by calling SoundPool.play(). Playing streams can be 88 * paused or resumed, and the application can also alter the pitch by 89 * adjusting the playback rate in real-time for doppler or synthesis 90 * effects.</p> 91 * 92 * <p>Note that since streams can be stopped due to resource constraints, the 93 * streamID is a reference to a particular instance of a stream. If the stream 94 * is stopped to allow a higher priority stream to play, the stream is no 95 * longer be valid. However, the application is allowed to call methods on 96 * the streamID without error. This may help simplify program logic since 97 * the application need not concern itself with the stream lifecycle.</p> 98 * 99 * <p>In our example, when the player has completed the level, the game 100 * logic should call SoundPool.release() to release all the native resources 101 * in use and then set the SoundPool reference to null. If the player starts 102 * another level, a new SoundPool is created, sounds are loaded, and play 103 * resumes.</p> 104 */ 105public class SoundPool 106{ 107 static { System.loadLibrary("soundpool"); } 108 109 private final static String TAG = "SoundPool"; 110 private final static boolean DEBUG = false; 111 112 private int mNativeContext; // accessed by native methods 113 114 private EventHandler mEventHandler; 115 private OnLoadCompleteListener mOnLoadCompleteListener; 116 117 private final Object mLock; 118 119 // SoundPool messages 120 // 121 // must match SoundPool.h 122 private static final int SAMPLE_LOADED = 1; 123 124 /** 125 * Constructor. Constructs a SoundPool object with the following 126 * characteristics: 127 * 128 * @param maxStreams the maximum number of simultaneous streams for this 129 * SoundPool object 130 * @param streamType the audio stream type as described in AudioManager 131 * For example, game applications will normally use 132 * {@link AudioManager#STREAM_MUSIC}. 133 * @param srcQuality the sample-rate converter quality. Currently has no 134 * effect. Use 0 for the default. 135 * @return a SoundPool object, or null if creation failed 136 */ 137 public SoundPool(int maxStreams, int streamType, int srcQuality) { 138 139 // do native setup 140 if (native_setup(new WeakReference(this), maxStreams, streamType, srcQuality) != 0) { 141 throw new RuntimeException("Native setup failed"); 142 } 143 mLock = new Object(); 144 145 // setup message handler 146 Looper looper; 147 if ((looper = Looper.myLooper()) != null) { 148 mEventHandler = new EventHandler(this, looper); 149 } else if ((looper = Looper.getMainLooper()) != null) { 150 mEventHandler = new EventHandler(this, looper); 151 } else { 152 mEventHandler = null; 153 } 154 155 } 156 157 /** 158 * Load the sound from the specified path. 159 * 160 * @param path the path to the audio file 161 * @param priority the priority of the sound. Currently has no effect. Use 162 * a value of 1 for future compatibility. 163 * @return a sound ID. This value can be used to play or unload the sound. 164 */ 165 public int load(String path, int priority) 166 { 167 // pass network streams to player 168 if (path.startsWith("http:")) 169 return _load(path, priority); 170 171 // try local path 172 int id = 0; 173 try { 174 File f = new File(path); 175 if (f != null) { 176 ParcelFileDescriptor fd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY); 177 if (fd != null) { 178 id = _load(fd.getFileDescriptor(), 0, f.length(), priority); 179 fd.close(); 180 } 181 } 182 } catch (java.io.IOException e) { 183 Log.e(TAG, "error loading " + path); 184 } 185 return id; 186 } 187 188 /** 189 * Load the sound from the specified APK resource. 190 * 191 * Note that the extension is dropped. For example, if you want to load 192 * a sound from the raw resource file "explosion.mp3", you would specify 193 * "R.raw.explosion" as the resource ID. Note that this means you cannot 194 * have both an "explosion.wav" and an "explosion.mp3" in the res/raw 195 * directory. 196 * 197 * @param context the application context 198 * @param resId the resource ID 199 * @param priority the priority of the sound. Currently has no effect. Use 200 * a value of 1 for future compatibility. 201 * @return a sound ID. This value can be used to play or unload the sound. 202 */ 203 public int load(Context context, int resId, int priority) { 204 AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId); 205 int id = 0; 206 if (afd != null) { 207 id = _load(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength(), priority); 208 try { 209 afd.close(); 210 } catch (java.io.IOException ex) { 211 //Log.d(TAG, "close failed:", ex); 212 } 213 } 214 return id; 215 } 216 217 /** 218 * Load the sound from an asset file descriptor. 219 * 220 * @param afd an asset file descriptor 221 * @param priority the priority of the sound. Currently has no effect. Use 222 * a value of 1 for future compatibility. 223 * @return a sound ID. This value can be used to play or unload the sound. 224 */ 225 public int load(AssetFileDescriptor afd, int priority) { 226 if (afd != null) { 227 long len = afd.getLength(); 228 if (len < 0) { 229 throw new AndroidRuntimeException("no length for fd"); 230 } 231 return _load(afd.getFileDescriptor(), afd.getStartOffset(), len, priority); 232 } else { 233 return 0; 234 } 235 } 236 237 /** 238 * Load the sound from a FileDescriptor. 239 * 240 * This version is useful if you store multiple sounds in a single 241 * binary. The offset specifies the offset from the start of the file 242 * and the length specifies the length of the sound within the file. 243 * 244 * @param fd a FileDescriptor object 245 * @param offset offset to the start of the sound 246 * @param length length of the sound 247 * @param priority the priority of the sound. Currently has no effect. Use 248 * a value of 1 for future compatibility. 249 * @return a sound ID. This value can be used to play or unload the sound. 250 */ 251 public int load(FileDescriptor fd, long offset, long length, int priority) { 252 return _load(fd, offset, length, priority); 253 } 254 255 private native final int _load(String uri, int priority); 256 257 private native final int _load(FileDescriptor fd, long offset, long length, int priority); 258 259 /** 260 * Unload a sound from a sound ID. 261 * 262 * Unloads the sound specified by the soundID. This is the value 263 * returned by the load() function. Returns true if the sound is 264 * successfully unloaded, false if the sound was already unloaded. 265 * 266 * @param soundID a soundID returned by the load() function 267 * @return true if just unloaded, false if previously unloaded 268 */ 269 public native final boolean unload(int soundID); 270 271 /** 272 * Play a sound from a sound ID. 273 * 274 * Play the sound specified by the soundID. This is the value 275 * returned by the load() function. Returns a non-zero streamID 276 * if successful, zero if it fails. The streamID can be used to 277 * further control playback. Note that calling play() may cause 278 * another sound to stop playing if the maximum number of active 279 * streams is exceeded. A loop value of -1 means loop forever, 280 * a value of 0 means don't loop, other values indicate the 281 * number of repeats, e.g. a value of 1 plays the audio twice. 282 * The playback rate allows the application to vary the playback 283 * rate (pitch) of the sound. A value of 1.0 means play back at 284 * the original frequency. A value of 2.0 means play back twice 285 * as fast, and a value of 0.5 means playback at half speed. 286 * 287 * @param soundID a soundID returned by the load() function 288 * @param leftVolume left volume value (range = 0.0 to 1.0) 289 * @param rightVolume right volume value (range = 0.0 to 1.0) 290 * @param priority stream priority (0 = lowest priority) 291 * @param loop loop mode (0 = no loop, -1 = loop forever) 292 * @param rate playback rate (1.0 = normal playback, range 0.5 to 2.0) 293 * @return non-zero streamID if successful, zero if failed 294 */ 295 public native final int play(int soundID, float leftVolume, float rightVolume, 296 int priority, int loop, float rate); 297 298 /** 299 * Pause a playback stream. 300 * 301 * Pause the stream specified by the streamID. This is the 302 * value returned by the play() function. If the stream is 303 * playing, it will be paused. If the stream is not playing 304 * (e.g. is stopped or was previously paused), calling this 305 * function will have no effect. 306 * 307 * @param streamID a streamID returned by the play() function 308 */ 309 public native final void pause(int streamID); 310 311 /** 312 * Resume a playback stream. 313 * 314 * Resume the stream specified by the streamID. This 315 * is the value returned by the play() function. If the stream 316 * is paused, this will resume playback. If the stream was not 317 * previously paused, calling this function will have no effect. 318 * 319 * @param streamID a streamID returned by the play() function 320 */ 321 public native final void resume(int streamID); 322 323 /** 324 * Pause all active streams. 325 * 326 * Pause all streams that are currently playing. This function 327 * iterates through all the active streams and pauses any that 328 * are playing. It also sets a flag so that any streams that 329 * are playing can be resumed by calling autoResume(). 330 * 331 * @hide 332 */ 333 public native final void autoPause(); 334 335 /** 336 * Resume all previously active streams. 337 * 338 * Automatically resumes all streams that were paused in previous 339 * calls to autoPause(). 340 * 341 * @hide 342 */ 343 public native final void autoResume(); 344 345 /** 346 * Stop a playback stream. 347 * 348 * Stop the stream specified by the streamID. This 349 * is the value returned by the play() function. If the stream 350 * is playing, it will be stopped. It also releases any native 351 * resources associated with this stream. If the stream is not 352 * playing, it will have no effect. 353 * 354 * @param streamID a streamID returned by the play() function 355 */ 356 public native final void stop(int streamID); 357 358 /** 359 * Set stream volume. 360 * 361 * Sets the volume on the stream specified by the streamID. 362 * This is the value returned by the play() function. The 363 * value must be in the range of 0.0 to 1.0. If the stream does 364 * not exist, it will have no effect. 365 * 366 * @param streamID a streamID returned by the play() function 367 * @param leftVolume left volume value (range = 0.0 to 1.0) 368 * @param rightVolume right volume value (range = 0.0 to 1.0) 369 */ 370 public native final void setVolume(int streamID, 371 float leftVolume, float rightVolume); 372 373 /** 374 * Change stream priority. 375 * 376 * Change the priority of the stream specified by the streamID. 377 * This is the value returned by the play() function. Affects the 378 * order in which streams are re-used to play new sounds. If the 379 * stream does not exist, it will have no effect. 380 * 381 * @param streamID a streamID returned by the play() function 382 */ 383 public native final void setPriority(int streamID, int priority); 384 385 /** 386 * Set loop mode. 387 * 388 * Change the loop mode. A loop value of -1 means loop forever, 389 * a value of 0 means don't loop, other values indicate the 390 * number of repeats, e.g. a value of 1 plays the audio twice. 391 * If the stream does not exist, it will have no effect. 392 * 393 * @param streamID a streamID returned by the play() function 394 * @param loop loop mode (0 = no loop, -1 = loop forever) 395 */ 396 public native final void setLoop(int streamID, int loop); 397 398 /** 399 * Change playback rate. 400 * 401 * The playback rate allows the application to vary the playback 402 * rate (pitch) of the sound. A value of 1.0 means playback at 403 * the original frequency. A value of 2.0 means playback twice 404 * as fast, and a value of 0.5 means playback at half speed. 405 * If the stream does not exist, it will have no effect. 406 * 407 * @param streamID a streamID returned by the play() function 408 * @param rate playback rate (1.0 = normal playback, range 0.5 to 2.0) 409 */ 410 public native final void setRate(int streamID, float rate); 411 412 /** 413 * Interface definition for a callback to be invoked when all the 414 * sounds are loaded. 415 * 416 * @hide 417 */ 418 public interface OnLoadCompleteListener 419 { 420 /** 421 * Called when a sound has completed loading. 422 * 423 * @param soundPool SoundPool object from the load() method 424 * @param soundPool the sample ID of the sound loaded. 425 * @param status the status of the load operation (0 = success) 426 */ 427 public void onLoadComplete(SoundPool soundPool, int sampleId, int status); 428 } 429 430 /** 431 * Sets the callback hook for the OnLoadCompleteListener. 432 * 433 * @hide 434 */ 435 public void setOnLoadCompleteListener(OnLoadCompleteListener listener) 436 { 437 synchronized(mLock) { 438 mOnLoadCompleteListener = listener; 439 } 440 } 441 442 private class EventHandler extends Handler 443 { 444 private SoundPool mSoundPool; 445 446 public EventHandler(SoundPool soundPool, Looper looper) { 447 super(looper); 448 mSoundPool = soundPool; 449 } 450 451 @Override 452 public void handleMessage(Message msg) { 453 switch(msg.what) { 454 case SAMPLE_LOADED: 455 if (DEBUG) Log.d(TAG, "Sample " + msg.arg1 + " loaded"); 456 synchronized(mLock) { 457 if (mOnLoadCompleteListener != null) { 458 mOnLoadCompleteListener.onLoadComplete(mSoundPool, msg.arg1, msg.arg2); 459 } 460 } 461 break; 462 default: 463 Log.e(TAG, "Unknown message type " + msg.what); 464 return; 465 } 466 } 467 } 468 469 // post event from native code to message handler 470 private static void postEventFromNative(Object weakRef, int msg, int arg1, int arg2, Object obj) 471 { 472 SoundPool soundPool = (SoundPool)((WeakReference)weakRef).get(); 473 if (soundPool == null) 474 return; 475 476 if (soundPool.mEventHandler != null) { 477 Message m = soundPool.mEventHandler.obtainMessage(msg, arg1, arg2, obj); 478 soundPool.mEventHandler.sendMessage(m); 479 } 480 } 481 482 /** 483 * Release the SoundPool resources. 484 * 485 * Release all memory and native resources used by the SoundPool 486 * object. The SoundPool can no longer be used and the reference 487 * should be set to null. 488 */ 489 public native final void release(); 490 491 private native final int native_setup(Object weakRef, int maxStreams, int streamType, int srcQuality); 492 493 protected void finalize() { release(); } 494} 495