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