在酒吧中的DJ打碟调动气氛,不同的听觉效果将热度带到最高。这其中的原理其实也就是我们的音频池所要实现
的效果。谁说我们程序员死板,今天就研究下这个好玩的东西。
在音频池中可以存放多个音乐,所以每个大小都不能超过一M。我们先将它存放在raw文件中,我们先给它放五个音效
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="play1"
android:text="1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="play2"
android:text="2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="play3"
android:text="3" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="play4"
android:text="4" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="play5"
android:text="5" />
然后开始java代码的编写
首先实例化一个SoundPool,给每个音效的点击事件添加一段音频
//实例化音频池(参数一:最多放的音频数量,参数二:音乐类型,参数三:音频质量,一般默认为0)
soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC,0);
public void play1(View view){
soundPool.load(this,R.raw.one,1);
}
public void play2(View view){
soundPool.load(this,R.raw.two,1);
}
public void play3(View view){
soundPool.load(this,R.raw.three,1);
}
public void play4(View view){
soundPool.load(this,R.raw.four,1);
}
public void play5(View view){
soundPool.load(this,R.raw.five,1);
}
接下来给音频设置加载完成的监听
//给音频池设置加载完成的监听
soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
@Override
public void onLoadComplete(SoundPool soundPool, int i, int i1) {
//参数一:加载完的id,二,三,四:五:
六:速率
soundPool.play(i,1,1,1,100,1);
}
});
}
最后写一个销毁事件
@Override
protected void onDestroy() {
super.onDestroy();
if(soundPool!=null){
soundPool.release();
soundPool=null;
}
}
音频池就大概可以实现了,我们可以根据自己的喜好设置不同的音频,不同排序不同速率等,很好玩的