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 17 package android.media; 18 19 import static android.media.AudioManager.AUDIO_SESSION_ID_GENERATE; 20 21 import android.annotation.NonNull; 22 import android.annotation.Nullable; 23 import android.content.Context; 24 import android.content.res.AssetFileDescriptor; 25 import android.os.Handler; 26 import android.os.Looper; 27 import android.os.Message; 28 import android.os.ParcelFileDescriptor; 29 import android.util.AndroidRuntimeException; 30 import android.util.Log; 31 32 import java.io.File; 33 import java.io.FileDescriptor; 34 import java.util.Objects; 35 import java.util.concurrent.atomic.AtomicReference; 36 37 38 /** 39 * The SoundPool class manages and plays audio resources for applications. 40 * 41 * <p>A SoundPool is a collection of sound samples that can be loaded into memory 42 * from a resource inside the APK or from a file in the file system. The 43 * SoundPool library uses the MediaCodec service to decode the audio 44 * into raw 16-bit PCM. This allows applications 45 * to ship with compressed streams without having to suffer the CPU load 46 * and latency of decompressing during playback.</p> 47 * 48 * <p>Soundpool sounds are expected to be short as they are 49 * predecoded into memory. Each decoded sound is internally limited to one 50 * megabyte storage, which represents approximately 5.6 seconds at 44.1kHz stereo 51 * (the duration is proportionally longer at lower sample rates or 52 * a channel mask of mono). A decoded audio sound will be truncated if it would 53 * exceed the per-sound one megabyte storage space.</p> 54 * 55 * <p>In addition to low-latency playback, SoundPool can also manage the number 56 * of audio streams being rendered at once. When the SoundPool object is 57 * constructed, the maxStreams parameter sets the maximum number of streams 58 * that can be played at a time from this single SoundPool. SoundPool tracks 59 * the number of active streams. If the maximum number of streams is exceeded, 60 * SoundPool will automatically stop a previously playing stream based first 61 * on priority and then by age within that priority. Limiting the maximum 62 * number of streams helps to cap CPU loading and reducing the likelihood that 63 * audio mixing will impact visuals or UI performance.</p> 64 * 65 * <p>Sounds can be looped by setting a non-zero loop value. A value of -1 66 * causes the sound to loop forever. In this case, the application must 67 * explicitly call the stop() function to stop the sound. Any other non-zero 68 * value will cause the sound to repeat the specified number of times, e.g. 69 * a value of 3 causes the sound to play a total of 4 times.</p> 70 * 71 * <p>The playback rate can also be changed. A playback rate of 1.0 causes 72 * the sound to play at its original frequency (resampled, if necessary, 73 * to the hardware output frequency). A playback rate of 2.0 causes the 74 * sound to play at twice its original frequency, and a playback rate of 75 * 0.5 causes it to play at half its original frequency. The playback 76 * rate range is 0.5 to 2.0.</p> 77 * 78 * <p>Priority runs low to high, i.e. higher numbers are higher priority. 79 * Priority is used when a call to play() would cause the number of active 80 * streams to exceed the value established by the maxStreams parameter when 81 * the SoundPool was created. In this case, the stream allocator will stop 82 * the lowest priority stream. If there are multiple streams with the same 83 * low priority, it will choose the oldest stream to stop. In the case 84 * where the priority of the new stream is lower than all the active 85 * streams, the new sound will not play and the play() function will return 86 * a streamID of zero.</p> 87 * 88 * <p>Let's examine a typical use case: A game consists of several levels of 89 * play. For each level, there is a set of unique sounds that are used only 90 * by that level. In this case, the game logic should create a new SoundPool 91 * object when the first level is loaded. The level data itself might contain 92 * the list of sounds to be used by this level. The loading logic iterates 93 * through the list of sounds calling the appropriate SoundPool.load() 94 * function. This should typically be done early in the process to allow time 95 * for decompressing the audio to raw PCM format before they are needed for 96 * playback.</p> 97 * 98 * <p>Once the sounds are loaded and play has started, the application can 99 * trigger sounds by calling SoundPool.play(). Playing streams can be 100 * paused or resumed, and the application can also alter the pitch by 101 * adjusting the playback rate in real-time for doppler or synthesis 102 * effects.</p> 103 * 104 * <p>Note that since streams can be stopped due to resource constraints, the 105 * streamID is a reference to a particular instance of a stream. If the stream 106 * is stopped to allow a higher priority stream to play, the stream is no 107 * longer valid. However, the application is allowed to call methods on 108 * the streamID without error. This may help simplify program logic since 109 * the application need not concern itself with the stream lifecycle.</p> 110 * 111 * <p>In our example, when the player has completed the level, the game 112 * logic should call SoundPool.release() to release all the native resources 113 * in use and then set the SoundPool reference to null. If the player starts 114 * another level, a new SoundPool is created, sounds are loaded, and play 115 * resumes.</p> 116 */ 117 public class SoundPool extends PlayerBase { 118 static { System.loadLibrary("soundpool"); } 119 120 // SoundPool messages 121 // 122 // must match SoundPool.h 123 private static final int SAMPLE_LOADED = 1; 124 125 private final static String TAG = "SoundPool"; 126 private final static boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); 127 128 private final AtomicReference<EventHandler> mEventHandler = new AtomicReference<>(null); 129 130 private long mNativeContext; // accessed by native methods 131 132 private boolean mHasAppOpsPlayAudio; 133 134 private final AudioAttributes mAttributes; 135 136 /** 137 * Constructor. Constructs a SoundPool object with the following 138 * characteristics: 139 * 140 * @param maxStreams the maximum number of simultaneous streams for this 141 * SoundPool object 142 * @param streamType the audio stream type as described in AudioManager 143 * For example, game applications will normally use 144 * {@link AudioManager#STREAM_MUSIC}. 145 * @param srcQuality the sample-rate converter quality. Currently has no 146 * effect. Use 0 for the default. 147 * @return a SoundPool object, or null if creation failed 148 * @deprecated use {@link SoundPool.Builder} instead to create and configure a 149 * SoundPool instance 150 */ SoundPool(int maxStreams, int streamType, int srcQuality)151 public SoundPool(int maxStreams, int streamType, int srcQuality) { 152 this(/*context=*/null, maxStreams, 153 new AudioAttributes.Builder().setInternalLegacyStreamType(streamType).build(), 154 AUDIO_SESSION_ID_GENERATE); 155 PlayerBase.deprecateStreamTypeForPlayback(streamType, "SoundPool", "SoundPool()"); 156 } 157 SoundPool(@ullable Context context, int maxStreams, @NonNull AudioAttributes attributes, int sessionId)158 private SoundPool(@Nullable Context context, int maxStreams, 159 @NonNull AudioAttributes attributes, int sessionId) { 160 super(attributes, AudioPlaybackConfiguration.PLAYER_TYPE_JAM_SOUNDPOOL); 161 162 // do native setup 163 if (native_setup(maxStreams, attributes, getCurrentOpPackageName()) != 0) { 164 throw new RuntimeException("Native setup failed"); 165 } 166 mAttributes = attributes; 167 168 baseRegisterPlayer(resolvePlaybackSessionId(context, sessionId)); 169 } 170 171 /** 172 * Release the SoundPool resources. 173 * 174 * Release all memory and native resources used by the SoundPool 175 * object. The SoundPool can no longer be used and the reference 176 * should be set to null. 177 */ release()178 public final void release() { 179 baseRelease(); 180 native_release(); 181 } 182 native_release()183 private native final void native_release(); 184 finalize()185 protected void finalize() { release(); } 186 187 /** 188 * Load the sound from the specified path. 189 * 190 * @param path the path to the audio file 191 * @param priority the priority of the sound. Currently has no effect. Use 192 * a value of 1 for future compatibility. 193 * @return a sound ID. This value can be used to play or unload the sound. 194 */ load(String path, int priority)195 public int load(String path, int priority) { 196 int id = 0; 197 try { 198 File f = new File(path); 199 ParcelFileDescriptor fd = ParcelFileDescriptor.open(f, 200 ParcelFileDescriptor.MODE_READ_ONLY); 201 if (fd != null) { 202 id = _load(fd.getFileDescriptor(), 0, f.length(), priority); 203 fd.close(); 204 } 205 } catch (java.io.IOException e) { 206 Log.e(TAG, "error loading " + path); 207 } 208 return id; 209 } 210 211 /** 212 * Load the sound from the specified APK resource. 213 * 214 * Note that the extension is dropped. For example, if you want to load 215 * a sound from the raw resource file "explosion.mp3", you would specify 216 * "R.raw.explosion" as the resource ID. Note that this means you cannot 217 * have both an "explosion.wav" and an "explosion.mp3" in the res/raw 218 * directory. 219 * 220 * @param context the application context 221 * @param resId the resource ID 222 * @param priority the priority of the sound. Currently has no effect. Use 223 * a value of 1 for future compatibility. 224 * @return a sound ID. This value can be used to play or unload the sound. 225 */ load(Context context, int resId, int priority)226 public int load(Context context, int resId, int priority) { 227 AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId); 228 int id = 0; 229 if (afd != null) { 230 id = _load(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength(), priority); 231 try { 232 afd.close(); 233 } catch (java.io.IOException ex) { 234 //Log.d(TAG, "close failed:", ex); 235 } 236 } 237 return id; 238 } 239 240 /** 241 * Load the sound from an asset file descriptor. 242 * 243 * @param afd an asset file descriptor 244 * @param priority the priority of the sound. Currently has no effect. Use 245 * a value of 1 for future compatibility. 246 * @return a sound ID. This value can be used to play or unload the sound. 247 */ load(AssetFileDescriptor afd, int priority)248 public int load(AssetFileDescriptor afd, int priority) { 249 if (afd != null) { 250 long len = afd.getLength(); 251 if (len < 0) { 252 throw new AndroidRuntimeException("no length for fd"); 253 } 254 return _load(afd.getFileDescriptor(), afd.getStartOffset(), len, priority); 255 } else { 256 return 0; 257 } 258 } 259 260 /** 261 * Load the sound from a FileDescriptor. 262 * 263 * This version is useful if you store multiple sounds in a single 264 * binary. The offset specifies the offset from the start of the file 265 * and the length specifies the length of the sound within the file. 266 * 267 * @param fd a FileDescriptor object 268 * @param offset offset to the start of the sound 269 * @param length length of the sound 270 * @param priority the priority of the sound. Currently has no effect. Use 271 * a value of 1 for future compatibility. 272 * @return a sound ID. This value can be used to play or unload the sound. 273 */ load(FileDescriptor fd, long offset, long length, int priority)274 public int load(FileDescriptor fd, long offset, long length, int priority) { 275 return _load(fd, offset, length, priority); 276 } 277 278 /** 279 * Unload a sound from a sound ID. 280 * 281 * Unloads the sound specified by the soundID. This is the value 282 * returned by the load() function. Returns true if the sound is 283 * successfully unloaded, false if the sound was already unloaded. 284 * 285 * @param soundID a soundID returned by the load() function 286 * @return true if just unloaded, false if previously unloaded 287 */ unload(int soundID)288 public native final boolean unload(int soundID); 289 290 /** 291 * Play a sound from a sound ID. 292 * 293 * Play the sound specified by the soundID. This is the value 294 * returned by the load() function. Returns a non-zero streamID 295 * if successful, zero if it fails. The streamID can be used to 296 * further control playback. Note that calling play() may cause 297 * another sound to stop playing if the maximum number of active 298 * streams is exceeded. A loop value of -1 means loop forever, 299 * a value of 0 means don't loop, other values indicate the 300 * number of repeats, e.g. a value of 1 plays the audio twice. 301 * The playback rate allows the application to vary the playback 302 * rate (pitch) of the sound. A value of 1.0 means play back at 303 * the original frequency. A value of 2.0 means play back twice 304 * as fast, and a value of 0.5 means playback at half speed. 305 * 306 * @param soundID a soundID returned by the load() function 307 * @param leftVolume left volume value (range = 0.0 to 1.0) 308 * @param rightVolume right volume value (range = 0.0 to 1.0) 309 * @param priority stream priority (0 = lowest priority) 310 * @param loop loop mode (0 = no loop, -1 = loop forever) 311 * @param rate playback rate (1.0 = normal playback, range 0.5 to 2.0) 312 * @return non-zero streamID if successful, zero if failed 313 */ play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)314 public final int play(int soundID, float leftVolume, float rightVolume, 315 int priority, int loop, float rate) { 316 // FIXME: b/174876164 implement device id for soundpool 317 baseStart(0); 318 return _play(soundID, leftVolume, rightVolume, priority, loop, rate, getPlayerIId()); 319 } 320 321 /** 322 * Pause a playback stream. 323 * 324 * Pause the stream specified by the streamID. This is the 325 * value returned by the play() function. If the stream is 326 * playing, it will be paused. If the stream is not playing 327 * (e.g. is stopped or was previously paused), calling this 328 * function will have no effect. 329 * 330 * @param streamID a streamID returned by the play() function 331 */ pause(int streamID)332 public native final void pause(int streamID); 333 334 /** 335 * Resume a playback stream. 336 * 337 * Resume the stream specified by the streamID. This 338 * is the value returned by the play() function. If the stream 339 * is paused, this will resume playback. If the stream was not 340 * previously paused, calling this function will have no effect. 341 * 342 * @param streamID a streamID returned by the play() function 343 */ resume(int streamID)344 public native final void resume(int streamID); 345 346 /** 347 * Pause all active streams. 348 * 349 * Pause all streams that are currently playing. This function 350 * iterates through all the active streams and pauses any that 351 * are playing. It also sets a flag so that any streams that 352 * are playing can be resumed by calling autoResume(). 353 */ autoPause()354 public native final void autoPause(); 355 356 /** 357 * Resume all previously active streams. 358 * 359 * Automatically resumes all streams that were paused in previous 360 * calls to autoPause(). 361 */ autoResume()362 public native final void autoResume(); 363 364 /** 365 * Stop a playback stream. 366 * 367 * Stop the stream specified by the streamID. This 368 * is the value returned by the play() function. If the stream 369 * is playing, it will be stopped. It also releases any native 370 * resources associated with this stream. If the stream is not 371 * playing, it will have no effect. 372 * 373 * @param streamID a streamID returned by the play() function 374 */ stop(int streamID)375 public native final void stop(int streamID); 376 377 /** 378 * Set stream volume. 379 * 380 * Sets the volume on the stream specified by the streamID. 381 * This is the value returned by the play() function. The 382 * value must be in the range of 0.0 to 1.0. If the stream does 383 * not exist, it will have no effect. 384 * 385 * @param streamID a streamID returned by the play() function 386 * @param leftVolume left volume value (range = 0.0 to 1.0) 387 * @param rightVolume right volume value (range = 0.0 to 1.0) 388 */ setVolume(int streamID, float leftVolume, float rightVolume)389 public final void setVolume(int streamID, float leftVolume, float rightVolume) { 390 // unlike other subclasses of PlayerBase, we are not calling 391 // baseSetVolume(leftVolume, rightVolume) as we need to keep track of each 392 // volume separately for each player, so we still send the command, but 393 // handle mute/unmute separately through playerSetVolume() 394 _setVolume(streamID, leftVolume, rightVolume); 395 } 396 397 @Override playerApplyVolumeShaper( @onNull VolumeShaper.Configuration configuration, @Nullable VolumeShaper.Operation operation)398 /* package */ int playerApplyVolumeShaper( 399 @NonNull VolumeShaper.Configuration configuration, 400 @Nullable VolumeShaper.Operation operation) { 401 return -1; 402 } 403 404 @Override playerGetVolumeShaperState(int id)405 /* package */ @Nullable VolumeShaper.State playerGetVolumeShaperState(int id) { 406 return null; 407 } 408 409 @Override playerSetVolume(boolean muting, float leftVolume, float rightVolume)410 void playerSetVolume(boolean muting, float leftVolume, float rightVolume) { 411 // not used here to control the player volume directly, but used to mute/unmute 412 _mute(muting); 413 } 414 415 @Override playerSetAuxEffectSendLevel(boolean muting, float level)416 int playerSetAuxEffectSendLevel(boolean muting, float level) { 417 // no aux send functionality so no-op 418 return AudioSystem.SUCCESS; 419 } 420 421 @Override playerStart()422 void playerStart() { 423 // FIXME implement resuming any paused sound 424 } 425 426 @Override playerPause()427 void playerPause() { 428 // FIXME implement pausing any playing sound 429 } 430 431 @Override playerStop()432 void playerStop() { 433 // FIXME implement pausing any playing sound 434 } 435 436 /** 437 * Similar, except set volume of all channels to same value. 438 * @hide 439 */ setVolume(int streamID, float volume)440 public void setVolume(int streamID, float volume) { 441 setVolume(streamID, volume, volume); 442 } 443 444 /** 445 * Change stream priority. 446 * 447 * Change the priority of the stream specified by the streamID. 448 * This is the value returned by the play() function. Affects the 449 * order in which streams are re-used to play new sounds. If the 450 * stream does not exist, it will have no effect. 451 * 452 * @param streamID a streamID returned by the play() function 453 */ setPriority(int streamID, int priority)454 public native final void setPriority(int streamID, int priority); 455 456 /** 457 * Set loop mode. 458 * 459 * Change the loop mode. A loop value of -1 means loop forever, 460 * a value of 0 means don't loop, other values indicate the 461 * number of repeats, e.g. a value of 1 plays the audio twice. 462 * If the stream does not exist, it will have no effect. 463 * 464 * @param streamID a streamID returned by the play() function 465 * @param loop loop mode (0 = no loop, -1 = loop forever) 466 */ setLoop(int streamID, int loop)467 public native final void setLoop(int streamID, int loop); 468 469 /** 470 * Change playback rate. 471 * 472 * The playback rate allows the application to vary the playback 473 * rate (pitch) of the sound. A value of 1.0 means playback at 474 * the original frequency. A value of 2.0 means playback twice 475 * as fast, and a value of 0.5 means playback at half speed. 476 * If the stream does not exist, it will have no effect. 477 * 478 * @param streamID a streamID returned by the play() function 479 * @param rate playback rate (1.0 = normal playback, range 0.5 to 2.0) 480 */ setRate(int streamID, float rate)481 public native final void setRate(int streamID, float rate); 482 483 public interface OnLoadCompleteListener { 484 /** 485 * Called when a sound has completed loading. 486 * 487 * @param soundPool SoundPool object from the load() method 488 * @param sampleId the sample ID of the sound loaded. 489 * @param status the status of the load operation (0 = success) 490 */ onLoadComplete(SoundPool soundPool, int sampleId, int status)491 public void onLoadComplete(SoundPool soundPool, int sampleId, int status); 492 } 493 494 /** 495 * Sets the callback hook for the OnLoadCompleteListener. 496 */ setOnLoadCompleteListener(OnLoadCompleteListener listener)497 public void setOnLoadCompleteListener(OnLoadCompleteListener listener) { 498 if (listener == null) { 499 mEventHandler.set(null); 500 return; 501 } 502 503 Looper looper; 504 if ((looper = Looper.myLooper()) != null) { 505 mEventHandler.set(new EventHandler(looper, listener)); 506 } else if ((looper = Looper.getMainLooper()) != null) { 507 mEventHandler.set(new EventHandler(looper, listener)); 508 } else { 509 mEventHandler.set(null); 510 } 511 } 512 _load(FileDescriptor fd, long offset, long length, int priority)513 private native final int _load(FileDescriptor fd, long offset, long length, int priority); 514 native_setup(int maxStreams, @NonNull Object attributes, @NonNull String opPackageName)515 private native int native_setup(int maxStreams, 516 @NonNull Object/*AudioAttributes*/ attributes, @NonNull String opPackageName); 517 _play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate, int playerIId)518 private native final int _play(int soundID, float leftVolume, float rightVolume, 519 int priority, int loop, float rate, int playerIId); 520 _setVolume(int streamID, float leftVolume, float rightVolume)521 private native final void _setVolume(int streamID, float leftVolume, float rightVolume); 522 _mute(boolean muting)523 private native final void _mute(boolean muting); 524 525 // post event from native code to message handler 526 @SuppressWarnings("unchecked") postEventFromNative(int msg, int arg1, int arg2, Object obj)527 private void postEventFromNative(int msg, int arg1, int arg2, Object obj) { 528 Handler eventHandler = mEventHandler.get(); 529 if (eventHandler == null) { 530 return; 531 } 532 Message message = eventHandler.obtainMessage(msg, arg1, arg2, obj); 533 eventHandler.sendMessage(message); 534 } 535 536 private final class EventHandler extends Handler { 537 private final OnLoadCompleteListener mOnLoadCompleteListener; 538 EventHandler(Looper looper, @NonNull OnLoadCompleteListener onLoadCompleteListener)539 EventHandler(Looper looper, @NonNull OnLoadCompleteListener onLoadCompleteListener) { 540 super(looper); 541 mOnLoadCompleteListener = onLoadCompleteListener; 542 } 543 544 @Override handleMessage(Message msg)545 public void handleMessage(Message msg) { 546 if (msg.what != SAMPLE_LOADED) { 547 Log.e(TAG, "Unknown message type " + msg.what); 548 return; 549 } 550 551 if (DEBUG) Log.d(TAG, "Sample " + msg.arg1 + " loaded"); 552 mOnLoadCompleteListener.onLoadComplete(SoundPool.this, msg.arg1, msg.arg2); 553 } 554 } 555 556 /** 557 * Builder class for {@link SoundPool} objects. 558 */ 559 public static class Builder { 560 private int mMaxStreams = 1; 561 private AudioAttributes mAudioAttributes; 562 private Context mContext; 563 private int mSessionId = AUDIO_SESSION_ID_GENERATE; 564 565 /** 566 * Constructs a new Builder with the defaults format values. 567 * If not provided, the maximum number of streams is 1 (see {@link #setMaxStreams(int)} to 568 * change it), and the audio attributes have a usage value of 569 * {@link AudioAttributes#USAGE_MEDIA} (see {@link #setAudioAttributes(AudioAttributes)} to 570 * change them). 571 */ Builder()572 public Builder() { 573 } 574 575 /** 576 * Sets the maximum of number of simultaneous streams that can be played simultaneously. 577 * @param maxStreams a value equal to 1 or greater. 578 * @return the same Builder instance 579 * @throws IllegalArgumentException 580 */ setMaxStreams(int maxStreams)581 public Builder setMaxStreams(int maxStreams) throws IllegalArgumentException { 582 if (maxStreams <= 0) { 583 throw new IllegalArgumentException( 584 "Strictly positive value required for the maximum number of streams"); 585 } 586 mMaxStreams = maxStreams; 587 return this; 588 } 589 590 /** 591 * Sets the {@link AudioAttributes}. For examples, game applications will use attributes 592 * built with usage information set to {@link AudioAttributes#USAGE_GAME}. 593 * @param attributes a non-null 594 * @return 595 */ setAudioAttributes(AudioAttributes attributes)596 public Builder setAudioAttributes(AudioAttributes attributes) 597 throws IllegalArgumentException { 598 if (attributes == null) { 599 throw new IllegalArgumentException("Invalid null AudioAttributes"); 600 } 601 mAudioAttributes = attributes; 602 return this; 603 } 604 605 /** 606 * Sets the session ID the {@link SoundPool} will be attached to. 607 * 608 * Note, that if there's a device specific session id associated with the context 609 * (see {@link Builder#setContext(Context)}), explicitly setting a session id using this 610 * method will override it. 611 * 612 * @param sessionId a strictly positive ID number retrieved from another player or 613 * allocated by {@link AudioManager} via {@link AudioManager#generateAudioSessionId()}, 614 * or {@link AudioManager#AUDIO_SESSION_ID_GENERATE}. 615 * @return the same {@link Builder} instance 616 * @throws IllegalArgumentException when sessionId is invalid. 617 */ setAudioSessionId(int sessionId)618 public @NonNull Builder setAudioSessionId(int sessionId) { 619 if ((sessionId != AUDIO_SESSION_ID_GENERATE) && (sessionId < 1)) { 620 throw new IllegalArgumentException("Invalid audio session ID " + sessionId); 621 } 622 mSessionId = sessionId; 623 return this; 624 } 625 626 /** 627 * Sets the context the SoundPool belongs to. 628 * 629 * The context will be used to pull information, such as 630 * {@link android.content.AttributionSource} and device specific audio session ids, 631 * which will be associated with the {@link SoundPool}. However, the context itself will 632 * not be retained by the {@link SoundPool} instance after initialization. 633 * 634 * @param context a non-null {@link Context} instance 635 * @return the same {@link Builder} instance. 636 */ setContext(@onNull Context context)637 public @NonNull Builder setContext(@NonNull Context context) { 638 mContext = Objects.requireNonNull(context); 639 return this; 640 } 641 build()642 public SoundPool build() { 643 if (mAudioAttributes == null) { 644 mAudioAttributes = new AudioAttributes.Builder() 645 .setUsage(AudioAttributes.USAGE_MEDIA).build(); 646 } 647 return new SoundPool(mContext, mMaxStreams, mAudioAttributes, mSessionId); 648 } 649 } 650 } 651