您的位置:首页 > 移动开发 > Android开发

Android自助餐之SoundPool

2016-05-23 15:06 471 查看

Android自助餐之SoundPool

Android自助餐之SoundPool

查看全套目录

SoundPool介绍

主要方法

使用方法

使用示例

查看全套目录

SoundPool介绍

SoundPool相对于MediaPlayer,用前者播放短但反应速度要求高的声音以及同时播放多个声音。

SoundPool使用独立的线程载入声音,SoundPool.OnLoadCompleteListener回调载入完成后的方法。

主要方法

加载声音。返回值为soundID。

priority参数无效,置1

若文件大于1M,则只加载前1M

int load(AssetFileDescriptor afd, int priority) //通过一个AssetFileDescriptor对象

int load(Context context, int resId, int priority) //通过一个资源ID

int load(String path, int priority) //通过指定的路径加载

int load(FileDescriptor fd, long offset, long length, int priority) //通过FileDescriptor加载


播放控制。

final int play(int soundID, float leftVolume, float rightVolume, int priority, int loop, float rate) //播放指定音频的音效,并返回一个streamID 。

//priority —— 流的优先级,值越大优先级高,影响当同时播放数量超出了最大支持数时SoundPool对该流的处理;

//loop —— 循环播放的次数,0为值播放一次,-1为无限循环,其他值为播放loop+1次(例如,3为一共播放4次).

//rate —— 播放的速率,范围0.5-2.0(0.5为一半速率,1.0为正常速率,2.0为两倍速率)

final void pause(int streamID) //暂停指定播放流的音效(streamID 应通过play()返回)。

final void resume(int streamID) //继续播放指定播放流的音效(streamID 应通过play()返回)。

final void stop(int streamID) //终止指定播放流的音效(streamID 应通过play()返回)。


释放资源。

final boolean unload(int soundID) //卸载一个指定的音频资源.

final void release() //释放SoundPool中的所有音频资源.


使用方法

构造声音池

SoundPool soundPool=new SoundPool(5,AudioManager.STREAM_MUSIC,0);


准备声音集

Map<Integer, Integer> soundMap=new HashMap<Integer, Integer>();

soundMap.put(1, soundPool.load(MainActivity.this, R.raw.ir_begin, 1));

soundMap.put(2, soundPool.load(MainActivity.this, R.raw.ir_end, 1));

soundMap.put(3, soundPool.load(MainActivity.this, R.raw.ir_inter, 1));

soundMap.put(4, soundPool.load(MainActivity.this, R.raw.tada, 1));

soundMap.put(5, soundPool.load(MainActivity.this, R.raw.zhong, 1));


播放一个音频

soundPool.play(soundMap.get(1), 1, 1, 0, 0, 1);


使用示例

public class MainActivity extends Activity {
//1.准备资源文件。在res资源目录中新建一个raw子目录,将需要加载的音频文件放入其中,比如加载了shiqishidaibeijingyinyue.mp3
private SoundPool soundPool;
private int soundId;
private boolean flag = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//2.实现soundPool对象
soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0); //分别对应声音池数量,AudioManager.STREAM_MUSIC 和 0

//3.使用soundPool加载声音,该操作位异步操作,如果资源很大,需要一定的时间
soundId = soundPool.load(this, R.raw.shiqishidaibeijingyinyue, 1);

//4.为声音池设定加载完成监听事件
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
flag = true;    //  表示加载完成
}
});
}
//5.播放操作
public void click(View view){
if(flag){
//  播放声音池中的文件, 可以指定播放音量,优先级 声音播放的速率
soundPool.play(soundId, 1.0f, 0.5f, 1, 0, 1.0f);
}else{
Toast.makeText(this, "正在加载,请稍后", 1).show();
}
}

//6.使用完全后,应该释放资源
@Override
protected void onDestroy() {
soundPool.release();
soundPool = null;
super.onDestroy();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: