一个大坑:SoundPool最多只能播放时长10s左右、大小70kb左右(这些值是我多次测试而来,并不确定)的音频!
官方文档
The SoundPool class manages and plays audio resources for applications.
SoundPool类管理和播放应用程序的音频资源。
A SoundPool is a collection of samples that can be loaded into memory from a resource inside the APK or from a file in the file system. The SoundPool library uses the MediaPlayer service to decode the audio into a raw 16-bit PCM mono or stereo stream. This allows applications to ship with compressed streams without having to suffer the CPU load and latency of decompressing during playback.
SoundPool是可以从APK内的资源或文件系统中的文件加载到内存中的样本集合。 SoundPool库使用MediaPlayer服务将音频解码为原始的16位PCM单声道或立体声流。 这允许应用程序使用压缩流进行传输,而不必在播放期间遭受CPU负载和解压缩的延迟。
In addition to low-latency playback, SoundPool can also manage the number of audio streams being rendered at once. When the SoundPool object is constructed, the maxStreams parameter sets the maximum number of streams that can be played at a time from this single SoundPool. SoundPool tracks the number of active streams. If the maximum number of streams is exceeded, SoundPool will automatically stop a previously playing stream based first on priority and then by age within that priority. Limiting the maximum number of streams helps to cap CPU loading and reducing the likelihood that audio mixing will impact visuals or UI performance.
除了低延迟播放之外,SoundPool还可以管理立即呈现的音频流的数量。当SoundPool对象被构造时,maxStreams参数设置从一个SoundPool可以一次播放的最大流数。 SoundPool跟踪活动流的数量。如果超过流的最大数量,SoundPool将首先优先按照该优先级的年龄自动停止先前播放的流。限制流的最大数量有助于加快CPU加载速度,并减少音频混合影响视觉效果或UI性能的可能性。
Sounds can be looped by setting a non-zero loop value. A value of -1 causes the sound to loop forever. In this case, the application must explicitly call the stop() function to stop the sound. Any other non-zero value will cause the sound to repeat the specified number of times, e.g. a value of 3 causes the sound to play a total of 4 times.
可以通过设置非零的值来循环播放声音。值为-1会使声音永久循环。在这种情况下,应用程序必须显式地调用stop()函数来停止声音。任何其他非零值将导致声音重复指定次数,例如一个值3会使声音共播放4次。
The playback rate can also be changed. A playback rate of 1.0 causes the sound to play at its original frequency (resampled, if necessary, to the hardware output frequency). A playback rate of 2.0 causes the sound to play at twice its original frequency, and a playback rate of 0.5 causes it to play at half its original frequency. The playback rate range is 0.5 to 2.0.
播放速度也可以改变。播放速率为1.0会导致声音以其原始频率播放(如有必要,重新采样到硬件输出频率)。 2.0的播放速度使声音以原始频率的两倍播放,并且播放速率为0.5使其以原始频率的一半播放。播放速度范围为0.5〜2.0。
Priority runs low to high, i.e. higher numbers are higher priority. Priority is used when a call to play() would cause the number of active streams to exceed the value established by the maxStreams parameter when the SoundPool was created. In this case, the stream allocator will stop the lowest priority stream. If there are multiple streams with the same low priority, it will choose the oldest stream to stop. In the case where the priority of the new stream is lower than all the active streams, the new sound will not play and the play() function will return a streamID of zero.
优先级从低到高,即较高的数字是较高的优先级。当play()的调用将导致,活动流的数量超过创建SoundPool时maxStreams参数建立的值时,将使用优先级。在这种情况下,流分配器将停止最低优先级流。如果存在多个具有相同低优先级的流,则它将选择最旧的流来停止。在新流的优先级低于所有活动流的情况下,新的声音将不会播放,并且play()函数将返回0的streamID。
Let's examine a typical use case: A game consists of several levels of play. For each level, there is a set of unique sounds that are used only by that level. In this case, the game logic should create a new SoundPool object when the first level is loaded. The level data itself might contain the list of sounds to be used by this level. The loading logic iterates through the list of sounds calling the appropriate SoundPool.load() function. This should typically be done early in the process to allow time for decompressing the audio to raw PCM format before they are needed for playback.
我们来研究一个典型的用例:游戏由几个级别组成。对于每个级别,都有一组仅由该级使用的唯一声音。在这种情况下,游戏逻辑应在第一级加载完成时创建一个新的SoundPool对象。级别数据本身可能包含此级别要使用的声音数据列表。加载逻辑迭代器通过声音列表调用相应的SoundPool.load()函数。这通常应该在进程的早期完成,以便在播放之前需要时间将音频解压缩为原始的PCM格式。
Once the sounds are loaded and play has started, the application can trigger sounds by calling SoundPool.play(). Playing streams can be paused or resumed, and the application can also alter the pitch by adjusting the playback rate in real-time for doppler or synthesis effects.
一旦声音被加载并且播放已经开始,应用程序可以通过调用SoundPool.play()来触发声音。播放流可以暂停或恢复,并且应用程序还可以通过实时调整多普勒或综合效果的播放速率来改变音调。
Note that since streams can be stopped due to resource constraints, the streamID is a reference to a particular instance of a stream. If the stream is stopped to allow a higher priority stream to play, the stream is no longer be valid. However, the application is allowed to call methods on the streamID without error. This may help simplify program logic since the application need not concern itself with the stream lifecycle.
注意,由于资源约束可以停止流,所以streamID是对流的特定实例的引用。如果流停止以允许更高优先级的流播放,流不再有效。但是,允许应用程序调用streamID上的方法,而不会出错。这可能有助于简化程序逻辑,因为应用程序不需要关注流生命周期。
In our example, when the player has completed the level, the game logic should call SoundPool.release() to release all the native resources in use and then set the SoundPool reference to null. If the player starts another level, a new SoundPool is created, sounds are loaded, and play resumes.
在我们的示例中,当玩家已经完成了级别时,游戏逻辑应该调用SoundPool.release()来释放所有正在使用的本地资源,然后将SoundPool引用设置为null。如果玩家开始另一个级别,则会创建一个新的SoundPool,声音被加载,播放恢复。
API 介绍
SoundPool(int maxStreams, int streamType, int srcQuality) This constructor was deprecated in API level 21. use SoundPool.Builder instead to create and configure a SoundPool instance- maxStream:同时播放的流的最大数量
- streamType:流的类型,一般为STREAM_MUSIC(具体在AudioManager类中列出)
- srcQuality:采样率转化质量,当前无效果,使用0作为默认值
对指定streamID的播放进行控制
- final void pause(int streamID) Pause a playback stream. 暂停播放
- Pause the stream specified by the streamID. This is the value returned by the play() function. If the stream is playing, it will be paused. If the stream is not playing (e.g. is stopped or was previously paused), calling this function will have no effect. 暂停streamID指定的流。 这是play()函数返回的值。 如果流正在播放,它将被暂停。 如果流未播放(例如,停止或先前已暂停),则调用此功能将不起作用。
- final void resume(int streamID) Resume a playback stream. 继续播放
- Resume the stream specified by the streamID. This is the value returned by the play() function. If the stream is paused, this will resume playback. If the stream was not previously paused, calling this function will have no effect.
- final void stop(int streamID) Stop a playback stream. 终止播放
- Stop the stream specified by the streamID. This is the value returned by the play() function. If the stream is playing, it will be stopped. It also releases any native resources associated with this stream. If the stream is not playing, it will have no effect.
对指定streamID的参数进行设置
- final void setLoop(int streamID, int loop) Set loop mode. 设置指定播放流的循环次数
- A loop value of -1 means loop forever, a value of 0 means don't loop, other values indicate the number of repeats, e.g. a value of 1 plays the audio twice. If the stream does not exist, it will have no effect.
- final void setPriority(int streamID, int priority) Change stream priority. 设置指定播放流的优先级
- Change the priority of the stream specified by the streamID. This is the value returned by the play() function. Affects the order in which streams are re-used to play new sounds. If the stream does not exist, it will have no effect.
- final void setRate(int streamID, float rate) Change playback rate. 设置指定播放流的播放速率
- The playback rate allows the application to vary the playback rate (pitch) of the sound. A value of 1.0 means playback at the original frequency. A value of 2.0 means playback twice as fast, and a value of 0.5 means playback at half speed. If the stream does not exist, it will have no effect.
- final void setVolume(int streamID, float leftVolume, float rightVolume) Set stream volume. 设置指定播放流的音量大小
- Sets the volume on the stream specified by the streamID. This is the value returned by the play() function. The value must be in the range of 0.0 to 1.0. If the stream does not exist, it will have no effect.
全部流的暂停播放与恢复播放
- final void autoPause() Pause all active streams.
- Pause all streams that are currently playing. This function iterates through all the active streams and pauses any that are playing. It also sets a flag so that any streams that are playing can be resumed by calling autoResume(). 暂停正在播放的所有流。 此函数遍历所有活动流并暂停播放任何正在播放的流。 它还设置一个标志,以便可以通过调用autoResume()来恢复正在播放的任何流。
- final void autoResume() Resume all previously active streams.
- Automatically resumes all streams that were paused in previous calls to autoPause().
资源释放
- final boolean unload(int soundID) Unload a sound from a sound ID. 卸载一个指定的音频资源
- Unloads the sound specified by the soundID. This is the value returned by the load() function. Returns true if the sound is successfully unloaded, false if the sound was already unloaded.
- final void release() Release the SoundPool resources. 释放所有资源
- Release all memory and native resources used by the SoundPool object. The SoundPool can no longer be used and the reference should be set to null.
设置监听
- void setOnLoadCompleteListener(SoundPool.OnLoadCompleteListener listener) Sets the callback hook for the OnLoadCompleteListener.
内部接口:SoundPool.OnLoadCompleteListener
- void onLoadComplete(SoundPool soundPool, int sampleId, int status) Called when a sound has completed loading.
加载音频资源【load】
可以通过以下四种途径来加载一个音频资源(API中指出,其中的priority参数目前没有效果,建议设置为1)
- 通过一个资源ID,int load(Context context, int resId, int priority)
- 通过指定的路径,int load(String path, int priority)
- 通过一个AssetFileDescriptor对象,int load(AssetFileDescriptor afd, int priority)
- 通过FileDescriptor,int load(FileDescriptor fd, long offset, long length, int priority)
一个SoundPool能同时管理多个音频,所以可以通过多次调用load函数来加载,如果加载成功将返回一个非0的soundID,用于播放时指定特定的音频。
四种load方式
- int ; i < array.length; i++) {
array[i] = i + "、" + array[i];
}
setListAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<>(Arrays.asList(array))));
soundPool = new SoundPool.Builder()
.setMaxStreams(5)
.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build())
.build();
soundPool.setOnLoadCompleteListener((soundPool1, sampleId, status) -> {
Log.i("bqt", "【onLoadComplete】" + sampleId + " " + status);//status : 0 = success
});
new Thread(this::initReseResources).start();//在子线程中初始化,特别是当有大量资源需要初始化时
}
private void initReseResources() {
Context context = this.getApplicationContext();//不管使用哪个Context,退出当前Activity后都会且会在延迟几秒钟后停止播放
//0-6,通过一个资源ID:Context context, int resId, int priority
soundIdList.add(soundPool.load(context, R.raw.s1_message, 0));
soundIdList.add(soundPool.load(context, R.raw.s10_42kb, 0));
soundIdList.add(soundPool.load(context, R.raw.caravan_15s_59kb, 0));
soundIdList.add(soundPool.load(context, R.raw.s8_67kb, 0));
soundIdList.add(soundPool.load(context, R.raw.ljsw_35s_68kb, 0));
soundIdList.add(soundPool.load(context, R.raw.ljsw_49s_102kb, 0));
soundIdList.add(soundPool.load(context, R.raw.hellow_tomorrow_6s_237kb, 0));
//7,通过指定的路径:String path, int priority
soundIdList.add(soundIdList.size(), 0);//如果文件不存在,则就不能set,否则会throw IndexOutOfBoundsException
String path = Environment.getExternalStorageDirectory() + File.separator + "caravan.mp3";
soundIdList.set(soundIdList.size() - 1, soundPool.load(path, 0));//注意:add和set时传入的index是不一样的!
//8-9,通过AssetFileDescriptor:AssetFileDescriptor afd, int priority
try {
soundIdList.add(soundIdList.size(), 0);//为防止异常后后续的代码执行不到导致index错乱,我们在一开始就直接add两个
soundIdList.add(soundIdList.size(), 0);
AssetFileDescriptor afd = getAssets().openFd("voice/caravan_15s_59kb.mp3");//openNonAssetFd
soundIdList.set(soundIdList.size() - 2, soundPool.load(afd, 0));
//通过FileDescriptor:FileDescriptor fd, long offset, long length, int priority
FileDescriptor fd = afd.getFileDescriptor();
long offset = afd.getStartOffset(), length = afd.getLength();
Log.i("bqt", "【afd】offset=" + offset + ",length=" + length);//offset=40786180,length=60480
soundIdList.set(soundIdList.size() - 1, soundPool.load(fd, offset + length / 2, length / 2, 0));
} catch (IOException e) {
e.printStackTrace();
}
//10
soundIdList.add(soundPool.load(getResources().openRawResourceFd(R.raw.s1_global), 0));
}
@Override
protected void onDestroy() {
super.onDestroy();
soundPool.release();//释放所有资源
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if (position <= 10) {
int soundID = soundIdList.get(position);
int loop = 0;//0 = no loop, -1 = loop forever
if (position == 0) loop = -1;
else if (position == 1) loop = 2;//3次
//播放指定soundID的音频:【int soundID】, float leftVolume, float rightVolume,int priority, 【int loop】, float rate
int streamID = soundPool.play(soundID, 1.0f, 1.0f, 1, loop, 1.0f);
Toast.makeText(this, "soundID=" + soundID + " streamID=" + streamID, Toast.LENGTH_SHORT).show();
//指定streamID的参数进行设置,这些参数都可以在播放时指定
soundPool.setLoop(streamID, 1);//实践证明,这里设置无效
switch (position) {
case 1:
soundPool.setRate(streamID, 1.5f);//大小并没有限制,但是一般不要小于0.5,不要大于1.5,否则声音严重失真
soundPool.setVolume(streamID, 1.0f, 0.1f);//只能降低,不能提高。The value must be in the range of 0.0 to 1.0
break;
case 2:
soundPool.setRate(streamID, 0.5f);
soundPool.setVolume(streamID, 0.1f, 1.0f);
break;
}
} else {
switch (position) {
case 11:
soundPool.autoPause();//可以多次调用,每次都是把当前正在播放的音乐暂停,并加入同一个列表中
break;
case 12:
soundPool.autoResume();//将所有暂停的音乐从暂停位置重新开始播放
break;
case 13:
Toast.makeText(this, "" + soundPool.unload(soundIdList.get(0)) + " " + soundPool.unload(soundIdList.get(1))
, Toast.LENGTH_SHORT).show();//unload并不能停止正在播放的音乐,特别是loop=-1的,仍会循环播放
break;
case 14:
soundPool.release();//会停止正在播放的所有音乐
break;
}
}
}
}
2017-7-5