• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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),
153                 maxStreams, attributes, getCurrentOpPackageName()) != 0) {
154             throw new RuntimeException("Native setup failed");
155         }
156         mAttributes = attributes;
157 
158         baseRegisterPlayer();
159     }
160 
161     /**
162      * Release the SoundPool resources.
163      *
164      * Release all memory and native resources used by the SoundPool
165      * object. The SoundPool can no longer be used and the reference
166      * should be set to null.
167      */
release()168     public final void release() {
169         baseRelease();
170         native_release();
171     }
172 
native_release()173     private native final void native_release();
174 
finalize()175     protected void finalize() { release(); }
176 
177     /**
178      * Load the sound from the specified path.
179      *
180      * @param path the path to the audio file
181      * @param priority the priority of the sound. Currently has no effect. Use
182      *                 a value of 1 for future compatibility.
183      * @return a sound ID. This value can be used to play or unload the sound.
184      */
load(String path, int priority)185     public int load(String path, int priority) {
186         int id = 0;
187         try {
188             File f = new File(path);
189             ParcelFileDescriptor fd = ParcelFileDescriptor.open(f,
190                     ParcelFileDescriptor.MODE_READ_ONLY);
191             if (fd != null) {
192                 id = _load(fd.getFileDescriptor(), 0, f.length(), priority);
193                 fd.close();
194             }
195         } catch (java.io.IOException e) {
196             Log.e(TAG, "error loading " + path);
197         }
198         return id;
199     }
200 
201     /**
202      * Load the sound from the specified APK resource.
203      *
204      * Note that the extension is dropped. For example, if you want to load
205      * a sound from the raw resource file "explosion.mp3", you would specify
206      * "R.raw.explosion" as the resource ID. Note that this means you cannot
207      * have both an "explosion.wav" and an "explosion.mp3" in the res/raw
208      * directory.
209      *
210      * @param context the application context
211      * @param resId the resource ID
212      * @param priority the priority of the sound. Currently has no effect. Use
213      *                 a value of 1 for future compatibility.
214      * @return a sound ID. This value can be used to play or unload the sound.
215      */
load(Context context, int resId, int priority)216     public int load(Context context, int resId, int priority) {
217         AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId);
218         int id = 0;
219         if (afd != null) {
220             id = _load(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength(), priority);
221             try {
222                 afd.close();
223             } catch (java.io.IOException ex) {
224                 //Log.d(TAG, "close failed:", ex);
225             }
226         }
227         return id;
228     }
229 
230     /**
231      * Load the sound from an asset file descriptor.
232      *
233      * @param afd an asset file descriptor
234      * @param priority the priority of the sound. Currently has no effect. Use
235      *                 a value of 1 for future compatibility.
236      * @return a sound ID. This value can be used to play or unload the sound.
237      */
load(AssetFileDescriptor afd, int priority)238     public int load(AssetFileDescriptor afd, int priority) {
239         if (afd != null) {
240             long len = afd.getLength();
241             if (len < 0) {
242                 throw new AndroidRuntimeException("no length for fd");
243             }
244             return _load(afd.getFileDescriptor(), afd.getStartOffset(), len, priority);
245         } else {
246             return 0;
247         }
248     }
249 
250     /**
251      * Load the sound from a FileDescriptor.
252      *
253      * This version is useful if you store multiple sounds in a single
254      * binary. The offset specifies the offset from the start of the file
255      * and the length specifies the length of the sound within the file.
256      *
257      * @param fd a FileDescriptor object
258      * @param offset offset to the start of the sound
259      * @param length length of the sound
260      * @param priority the priority of the sound. Currently has no effect. Use
261      *                 a value of 1 for future compatibility.
262      * @return a sound ID. This value can be used to play or unload the sound.
263      */
load(FileDescriptor fd, long offset, long length, int priority)264     public int load(FileDescriptor fd, long offset, long length, int priority) {
265         return _load(fd, offset, length, priority);
266     }
267 
268     /**
269      * Unload a sound from a sound ID.
270      *
271      * Unloads the sound specified by the soundID. This is the value
272      * returned by the load() function. Returns true if the sound is
273      * successfully unloaded, false if the sound was already unloaded.
274      *
275      * @param soundID a soundID returned by the load() function
276      * @return true if just unloaded, false if previously unloaded
277      */
unload(int soundID)278     public native final boolean unload(int soundID);
279 
280     /**
281      * Play a sound from a sound ID.
282      *
283      * Play the sound specified by the soundID. This is the value
284      * returned by the load() function. Returns a non-zero streamID
285      * if successful, zero if it fails. The streamID can be used to
286      * further control playback. Note that calling play() may cause
287      * another sound to stop playing if the maximum number of active
288      * streams is exceeded. A loop value of -1 means loop forever,
289      * a value of 0 means don't loop, other values indicate the
290      * number of repeats, e.g. a value of 1 plays the audio twice.
291      * The playback rate allows the application to vary the playback
292      * rate (pitch) of the sound. A value of 1.0 means play back at
293      * the original frequency. A value of 2.0 means play back twice
294      * as fast, and a value of 0.5 means playback at half speed.
295      *
296      * @param soundID a soundID returned by the load() function
297      * @param leftVolume left volume value (range = 0.0 to 1.0)
298      * @param rightVolume right volume value (range = 0.0 to 1.0)
299      * @param priority stream priority (0 = lowest priority)
300      * @param loop loop mode (0 = no loop, -1 = loop forever)
301      * @param rate playback rate (1.0 = normal playback, range 0.5 to 2.0)
302      * @return non-zero streamID if successful, zero if failed
303      */
play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)304     public final int play(int soundID, float leftVolume, float rightVolume,
305             int priority, int loop, float rate) {
306         baseStart();
307         return _play(soundID, leftVolume, rightVolume, priority, loop, rate);
308     }
309 
310     /**
311      * Pause a playback stream.
312      *
313      * Pause the stream specified by the streamID. This is the
314      * value returned by the play() function. If the stream is
315      * playing, it will be paused. If the stream is not playing
316      * (e.g. is stopped or was previously paused), calling this
317      * function will have no effect.
318      *
319      * @param streamID a streamID returned by the play() function
320      */
pause(int streamID)321     public native final void pause(int streamID);
322 
323     /**
324      * Resume a playback stream.
325      *
326      * Resume the stream specified by the streamID. This
327      * is the value returned by the play() function. If the stream
328      * is paused, this will resume playback. If the stream was not
329      * previously paused, calling this function will have no effect.
330      *
331      * @param streamID a streamID returned by the play() function
332      */
resume(int streamID)333     public native final void resume(int streamID);
334 
335     /**
336      * Pause all active streams.
337      *
338      * Pause all streams that are currently playing. This function
339      * iterates through all the active streams and pauses any that
340      * are playing. It also sets a flag so that any streams that
341      * are playing can be resumed by calling autoResume().
342      */
autoPause()343     public native final void autoPause();
344 
345     /**
346      * Resume all previously active streams.
347      *
348      * Automatically resumes all streams that were paused in previous
349      * calls to autoPause().
350      */
autoResume()351     public native final void autoResume();
352 
353     /**
354      * Stop a playback stream.
355      *
356      * Stop the stream specified by the streamID. This
357      * is the value returned by the play() function. If the stream
358      * is playing, it will be stopped. It also releases any native
359      * resources associated with this stream. If the stream is not
360      * playing, it will have no effect.
361      *
362      * @param streamID a streamID returned by the play() function
363      */
stop(int streamID)364     public native final void stop(int streamID);
365 
366     /**
367      * Set stream volume.
368      *
369      * Sets the volume on the stream specified by the streamID.
370      * This is the value returned by the play() function. The
371      * value must be in the range of 0.0 to 1.0. If the stream does
372      * not exist, it will have no effect.
373      *
374      * @param streamID a streamID returned by the play() function
375      * @param leftVolume left volume value (range = 0.0 to 1.0)
376      * @param rightVolume right volume value (range = 0.0 to 1.0)
377      */
setVolume(int streamID, float leftVolume, float rightVolume)378     public final void setVolume(int streamID, float leftVolume, float rightVolume) {
379         // unlike other subclasses of PlayerBase, we are not calling
380         // baseSetVolume(leftVolume, rightVolume) as we need to keep track of each
381         // volume separately for each player, so we still send the command, but
382         // handle mute/unmute separately through playerSetVolume()
383         _setVolume(streamID, leftVolume, rightVolume);
384     }
385 
386     @Override
playerApplyVolumeShaper( @onNull VolumeShaper.Configuration configuration, @Nullable VolumeShaper.Operation operation)387     /* package */ int playerApplyVolumeShaper(
388             @NonNull VolumeShaper.Configuration configuration,
389             @Nullable VolumeShaper.Operation operation) {
390         return -1;
391     }
392 
393     @Override
playerGetVolumeShaperState(int id)394     /* package */ @Nullable VolumeShaper.State playerGetVolumeShaperState(int id) {
395         return null;
396     }
397 
398     @Override
playerSetVolume(boolean muting, float leftVolume, float rightVolume)399     void playerSetVolume(boolean muting, float leftVolume, float rightVolume) {
400         // not used here to control the player volume directly, but used to mute/unmute
401         _mute(muting);
402     }
403 
404     @Override
playerSetAuxEffectSendLevel(boolean muting, float level)405     int playerSetAuxEffectSendLevel(boolean muting, float level) {
406         // no aux send functionality so no-op
407         return AudioSystem.SUCCESS;
408     }
409 
410     @Override
playerStart()411     void playerStart() {
412         // FIXME implement resuming any paused sound
413     }
414 
415     @Override
playerPause()416     void playerPause() {
417         // FIXME implement pausing any playing sound
418     }
419 
420     @Override
playerStop()421     void playerStop() {
422         // FIXME implement pausing any playing sound
423     }
424 
425     /**
426      * Similar, except set volume of all channels to same value.
427      * @hide
428      */
setVolume(int streamID, float volume)429     public void setVolume(int streamID, float volume) {
430         setVolume(streamID, volume, volume);
431     }
432 
433     /**
434      * Change stream priority.
435      *
436      * Change the priority of the stream specified by the streamID.
437      * This is the value returned by the play() function. Affects the
438      * order in which streams are re-used to play new sounds. If the
439      * stream does not exist, it will have no effect.
440      *
441      * @param streamID a streamID returned by the play() function
442      */
setPriority(int streamID, int priority)443     public native final void setPriority(int streamID, int priority);
444 
445     /**
446      * Set loop mode.
447      *
448      * Change the loop mode. A loop value of -1 means loop forever,
449      * a value of 0 means don't loop, other values indicate the
450      * number of repeats, e.g. a value of 1 plays the audio twice.
451      * If the stream does not exist, it will have no effect.
452      *
453      * @param streamID a streamID returned by the play() function
454      * @param loop loop mode (0 = no loop, -1 = loop forever)
455      */
setLoop(int streamID, int loop)456     public native final void setLoop(int streamID, int loop);
457 
458     /**
459      * Change playback rate.
460      *
461      * The playback rate allows the application to vary the playback
462      * rate (pitch) of the sound. A value of 1.0 means playback at
463      * the original frequency. A value of 2.0 means playback twice
464      * as fast, and a value of 0.5 means playback at half speed.
465      * If the stream does not exist, it will have no effect.
466      *
467      * @param streamID a streamID returned by the play() function
468      * @param rate playback rate (1.0 = normal playback, range 0.5 to 2.0)
469      */
setRate(int streamID, float rate)470     public native final void setRate(int streamID, float rate);
471 
472     public interface OnLoadCompleteListener {
473         /**
474          * Called when a sound has completed loading.
475          *
476          * @param soundPool SoundPool object from the load() method
477          * @param sampleId the sample ID of the sound loaded.
478          * @param status the status of the load operation (0 = success)
479          */
onLoadComplete(SoundPool soundPool, int sampleId, int status)480         public void onLoadComplete(SoundPool soundPool, int sampleId, int status);
481     }
482 
483     /**
484      * Sets the callback hook for the OnLoadCompleteListener.
485      */
setOnLoadCompleteListener(OnLoadCompleteListener listener)486     public void setOnLoadCompleteListener(OnLoadCompleteListener listener) {
487         if (listener == null) {
488             mEventHandler.set(null);
489             return;
490         }
491 
492         Looper looper;
493         if ((looper = Looper.myLooper()) != null) {
494             mEventHandler.set(new EventHandler(looper, listener));
495         } else if ((looper = Looper.getMainLooper()) != null) {
496             mEventHandler.set(new EventHandler(looper, listener));
497         } else {
498             mEventHandler.set(null);
499         }
500     }
501 
_load(FileDescriptor fd, long offset, long length, int priority)502     private native final int _load(FileDescriptor fd, long offset, long length, int priority);
503 
native_setup(Object weakRef, int maxStreams, @NonNull Object attributes, @NonNull String opPackageName)504     private native final int native_setup(Object weakRef, int maxStreams,
505             @NonNull Object/*AudioAttributes*/ attributes, @NonNull String opPackageName);
506 
_play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate)507     private native final int _play(int soundID, float leftVolume, float rightVolume,
508             int priority, int loop, float rate);
509 
_setVolume(int streamID, float leftVolume, float rightVolume)510     private native final void _setVolume(int streamID, float leftVolume, float rightVolume);
511 
_mute(boolean muting)512     private native final void _mute(boolean muting);
513 
514     // post event from native code to message handler
515     @SuppressWarnings("unchecked")
postEventFromNative(Object ref, int msg, int arg1, int arg2, Object obj)516     private static void postEventFromNative(Object ref, int msg, int arg1, int arg2, Object obj) {
517         SoundPool soundPool = ((WeakReference<SoundPool>) ref).get();
518         if (soundPool == null) {
519             return;
520         }
521 
522         Handler eventHandler = soundPool.mEventHandler.get();
523         if (eventHandler == null) {
524             return;
525         }
526 
527         Message message = eventHandler.obtainMessage(msg, arg1, arg2, obj);
528         eventHandler.sendMessage(message);
529     }
530 
531     private final class EventHandler extends Handler {
532         private final OnLoadCompleteListener mOnLoadCompleteListener;
533 
EventHandler(Looper looper, @NonNull OnLoadCompleteListener onLoadCompleteListener)534         EventHandler(Looper looper, @NonNull OnLoadCompleteListener onLoadCompleteListener) {
535             super(looper);
536             mOnLoadCompleteListener = onLoadCompleteListener;
537         }
538 
539         @Override
handleMessage(Message msg)540         public void handleMessage(Message msg) {
541             if (msg.what != SAMPLE_LOADED) {
542                 Log.e(TAG, "Unknown message type " + msg.what);
543                 return;
544             }
545 
546             if (DEBUG) Log.d(TAG, "Sample " + msg.arg1 + " loaded");
547             mOnLoadCompleteListener.onLoadComplete(SoundPool.this, msg.arg1, msg.arg2);
548         }
549     }
550 
551     /**
552      * Builder class for {@link SoundPool} objects.
553      */
554     public static class Builder {
555         private int mMaxStreams = 1;
556         private AudioAttributes mAudioAttributes;
557 
558         /**
559          * Constructs a new Builder with the defaults format values.
560          * If not provided, the maximum number of streams is 1 (see {@link #setMaxStreams(int)} to
561          * change it), and the audio attributes have a usage value of
562          * {@link AudioAttributes#USAGE_MEDIA} (see {@link #setAudioAttributes(AudioAttributes)} to
563          * change them).
564          */
Builder()565         public Builder() {
566         }
567 
568         /**
569          * Sets the maximum of number of simultaneous streams that can be played simultaneously.
570          * @param maxStreams a value equal to 1 or greater.
571          * @return the same Builder instance
572          * @throws IllegalArgumentException
573          */
setMaxStreams(int maxStreams)574         public Builder setMaxStreams(int maxStreams) throws IllegalArgumentException {
575             if (maxStreams <= 0) {
576                 throw new IllegalArgumentException(
577                         "Strictly positive value required for the maximum number of streams");
578             }
579             mMaxStreams = maxStreams;
580             return this;
581         }
582 
583         /**
584          * Sets the {@link AudioAttributes}. For examples, game applications will use attributes
585          * built with usage information set to {@link AudioAttributes#USAGE_GAME}.
586          * @param attributes a non-null
587          * @return
588          */
setAudioAttributes(AudioAttributes attributes)589         public Builder setAudioAttributes(AudioAttributes attributes)
590                 throws IllegalArgumentException {
591             if (attributes == null) {
592                 throw new IllegalArgumentException("Invalid null AudioAttributes");
593             }
594             mAudioAttributes = attributes;
595             return this;
596         }
597 
build()598         public SoundPool build() {
599             if (mAudioAttributes == null) {
600                 mAudioAttributes = new AudioAttributes.Builder()
601                         .setUsage(AudioAttributes.USAGE_MEDIA).build();
602             }
603             return new SoundPool(mMaxStreams, mAudioAttributes);
604         }
605     }
606 }
607