SoundPool.java revision cef302d0950a02fdc6920475d0c357d3949e85c3
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
29/**
30 * The SoundPool class manages and plays audio resources for applications.
31 *
32 * <p>A SoundPool is a collection of samples that can be loaded into memory
33 * from a resource inside the APK or from a file in the file system. The
34 * SoundPool library uses the MediaPlayer service to decode the audio
35 * into a raw 16-bit PCM mono or stereo stream. This allows applications
36 * to ship with compressed streams without having to suffer the CPU load
37 * and latency of decompressing during playback.</p>
38 *
39 * <p>In addition to low-latency playback, SoundPool can also manage the number
40 * of audio streams being rendered at once. When the SoundPool object is
41 * constructed, the maxStreams parameter sets the maximum number of streams
42 * that can be played at a time from this single SoundPool. SoundPool tracks
43 * the number of active streams. If the maximum number of streams is exceeded,
44 * SoundPool will automatically stop a previously playing stream based first
45 * on priority and then by age within that priority. Limiting the maximum
46 * number of streams helps to cap CPU loading and reducing the likelihood that
47 * audio mixing will impact visuals or UI performance.</p>
48 *
49 * <p>Priority runs low to high, i.e. higher numbers are higher priority.
50 * Priority is used when a call to play() would cause the number of active
51 * streams to exceed the value established by the maxStreams parameter when
52 * the SoundPool was created. In this case, the stream allocator will stop
53 * the lowest priority stream. If there are multiple streams with the same
54 * low priority, it will choose the oldest stream to stop. In the case
55 * where the priority of the new stream is lower than all the active
56 * streams, the new sound will not play and the play() function will return
57 * a streamID of zero.</p>
58 *
59 * <p>Let's examine a typical use case: A game consists of several levels of
60 * play. For each level, there is a set of unique sounds that are used only
61 * by that level. In this case, the game logic should create a new SoundPool
62 * object when the first level is loaded. The level data itself might contain
63 * the list of sounds to be used by this level. The loading logic iterates
64 * through the list of sounds calling the appropriate SoundPool.load()
65 * function. This should typically be done early in the process to allow time
66 * for decompressing the audio to raw PCM format before they are needed for
67 * playback.</p>
68 *
69 * <p>Once the sounds are loaded and play has started, the application can
70 * trigger sounds by calling SoundPool.play(). Playing streams can be
71 * paused or resumed, and the application can also alter the pitch by
72 * adjusting the playback rate in real-time for doppler or synthesis
73 * effects.</p>
74 *
75 * <p>In our example, when the player has completed the level, the game
76 * logic should call SoundPool.release() to release all the native resources
77 * in use and then set the SoundPool reference to null. If the player starts
78 * another level, a new SoundPool is created, sounds are loaded, and play
79 * resumes.</p>
80 */
81public class SoundPool
82{
83    static { System.loadLibrary("soundpool"); }
84
85    private final static String TAG = "SoundPool";
86
87    private int mNativeContext; // accessed by native methods
88
89    /**
90     * Constructor. Constructs a SoundPool object with the following
91     * characteristics:
92     *
93     * @param maxStreams the maximum number of simultaneous streams for this
94     *                   SoundPool object
95     * @param streamType the audio stream type as described in AudioManager
96     *                   For example, game applications will normally use
97     *                   {@link AudioManager#STREAM_MUSIC}.
98     * @param srcQuality the sample-rate converter quality. Currently has no
99     *                   effect. Use 0 for the default.
100     * @return a SoundPool object, or null if creation failed
101     */
102    public SoundPool(int maxStreams, int streamType, int srcQuality) {
103        native_setup(new WeakReference<SoundPool>(this), maxStreams, streamType, srcQuality);
104    }
105
106    /**
107     * Load the sound from the specified path
108     *
109     * @param path the path to the audio file
110     * @param priority the priority of the sound. Currently has no effect.
111     * @return a sound ID. This value can be used to play or unload the sound.
112     */
113    public int load(String path, int priority)
114    {
115        // pass network streams to player
116        if (path.startsWith("http:"))
117            return _load(path, priority);
118
119        // try local path
120        int id = 0;
121        try {
122            File f = new File(path);
123            if (f != null) {
124                ParcelFileDescriptor fd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
125                if (fd != null) {
126                    id = _load(fd.getFileDescriptor(), 0, f.length(), priority);
127                    //Log.v(TAG, "close fd");
128                    fd.close();
129                }
130            }
131        } catch (java.io.IOException e) {}
132        return id;
133    }
134
135    /**
136     * Load the sound from the specified APK resource
137     *
138     * <p>Note that the extension is dropped. For example, if you want to load
139     * a sound from the raw resource file "explosion.mp3", you would specify
140     * "R.raw.explosion" as the resource ID. Note that this means you cannot
141     * have both an "explosion.wav" and an "explosion.mp3" in the res/raw
142     * directory.</p>
143     *
144     * @param context the application context
145     * @param resId the resource ID
146     * @param priority the priority of the sound. Currently has no effect.
147     * @return a sound ID. This value can be used to play or unload the sound.
148     */
149    public int load(Context context, int resId, int priority) {
150        AssetFileDescriptor afd = context.getResources().openRawResourceFd(resId);
151        int id = 0;
152        if (afd != null) {
153            id = _load(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength(), priority);
154            try {
155                //Log.v(TAG, "close fd");
156                afd.close();
157            } catch (java.io.IOException ex) {
158                //Log.d(TAG, "close failed:", ex);
159            }
160        }
161        return id;
162    }
163
164    /**
165     * Load the sound from an asset file descriptor
166     *
167     * @param afd an asset file descriptor
168     * @param priority the priority of the sound. Currently has no effect.
169     * @return a sound ID. This value can be used to play or unload the sound.
170     */
171    public int load(AssetFileDescriptor afd, int priority) {
172        if (afd != null) {
173            long len = afd.getLength();
174            if (len < 0) {
175                throw new AndroidRuntimeException("no length for fd");
176            }
177            return _load(afd.getFileDescriptor(), afd.getStartOffset(), len, priority);
178        } else {
179            return 0;
180        }
181    }
182
183    /**
184     * Load the sound from a FileDescriptor
185     *
186     * <p>This version is useful if you store multiple sounds in a single
187     * binary. The offset specifies the offset from the start of the file
188     * and the length specifies the length of the sound within the file.</p>
189     *
190     * @param fd a FileDescriptor object
191     * @param offset offset to the start of the sound
192     * @param length length of the sound
193     * @param priority the priority of the sound. Currently has no effect.
194     * @return a sound ID. This value can be used to play or unload the sound.
195     */
196    public int load(FileDescriptor fd, long offset, long length, int priority) {
197        return _load(fd, offset, length, priority);
198    }
199
200    private native final int _load(String uri, int priority);
201
202    private native final int _load(FileDescriptor fd, long offset, long length, int priority);
203
204    /**
205     * Unload a sound from a sound ID
206     *
207     * <p>Unloads the sound specified by the soundID. This is the value
208     * returned by the load() function. Returns true if the sound is
209     * successfully unloaded, false if the sound was already unloaded.</p>
210     *
211     * @param soundID a soundID returned by the load() function
212     * @return true if just unloaded, false if previously unloaded
213     */
214    public native final boolean unload(int soundID);
215
216    /**
217     * Play a sound from a sound ID
218     *
219     * <p>Play the sound specified by the soundID. This is the value
220     * returned by the load() function. Returns a non-zero streamID
221     * if successful, zero if it fails. The streamID can be used to
222     * further control playback. Note that calling play() may cause
223     * another sound to stop playing if the maximum number of active
224     * streams is exceeded.</p>
225     *
226     * @param soundID a soundID returned by the load() function
227     * @return non-zero streamID if successful, zero if failed
228     */
229    public native final int play(int soundID, float leftVolume, float rightVolume,
230            int priority, int loop, float rate);
231
232    /**
233     * Pause a playback stream
234     *
235     * <p>Pause the stream specified by the streamID. This is the
236     * value returned by the play() function. If the stream is
237     * playing, it will be paused. If the stream is not playing
238     * (e.g. is stopped or was previously paused), calling this
239     * function will have no effect.</p>
240     *
241     * @param streamID a streamID returned by the play() function
242     */
243    public native final void pause(int streamID);
244
245    /**
246     * Resume a playback stream
247     *
248     * <p>Resume the stream specified by the streamID. This
249     * is the value returned by the play() function. If the stream
250     * is paused, this will resume playback. If the stream was not
251     * previously paused, calling this function will have no effect.</p>
252     *
253     * @param streamID a streamID returned by the play() function
254     */
255    public native final void resume(int streamID);
256
257    /**
258     * Stop a playback stream
259     *
260     * <p>Stop the stream specified by the streamID. This
261     * is the value returned by the play() function. If the stream
262     * is playing, it will be stopped. It also releases any native
263     * resources associated with this stream. If the stream is not
264     * playing, it will have no effect.</p>
265     *
266     * @param streamID a streamID returned by the play() function
267     */
268    public native final void stop(int streamID);
269
270    /**
271     * Set stream volume
272     *
273     * <p>Sets the volume on the stream specified by the streamID.
274     * This is the value returned by the play() function. The
275     * value must be in the range of 0.0 to 1.0. If the stream does
276     * not exist, it will have no effect.</p>
277     *
278     * @param streamID a streamID returned by the play() function
279     * @param leftVolume left volume value (range = 0.0 to 1.0)
280     * @param rightVolume right volume value (range = 0.0 to 1.0)
281     */
282    public native final void setVolume(int streamID,
283            float leftVolume, float rightVolume);
284
285    /**
286     * Change stream priority
287     *
288     * <p>Change the priority of the stream specified by the streamID.
289     * This is the value returned by the play() function. Affects the
290     * order in which streams are re-used to play new sounds.
291     *
292     * @param streamID a streamID returned by the play() function
293     */
294    public native final void setPriority(int streamID, int priority);
295
296    /**
297     * Change stream priority
298     *
299     * <p>Change the priority of the stream specified by the streamID.
300     * This is the value returned by the play() function. Affects the
301     * order in which streams are re-used to play new sounds.
302     *
303     * @param streamID a streamID returned by the play() function
304     */
305    public native final void setLoop(int streamID, int loop);
306
307    public native final void setRate(int streamID, float rate);
308
309    public native final void release();
310
311    private native final void native_setup(Object mediaplayer_this,
312            int maxStreams, int streamType, int srcQuality);
313
314    protected void finalize() { release(); }
315}
316