在实际项目中我们总会遇到要播放音频文件,其实一个MediaPlayer足够大家使用了,但是如果我们在点击按钮的时候要播放声音呢,这个在游戏中使用的非常普遍?当然其实也可以用MediaPlayer来做,但是对性能是极大的浪费,杀鸡焉用牛刀。这篇文章就带大家来学习下android中的另一款音频播放控件SoundPool,下面开始学习了!
1.先来看下API,了解下大概的调用方法和流程。
https://developer.android.google.cn/reference/android/media/SoundPool.html 附上链接地址,有不懂得大家可以自行翻译或者百度。
The SoundPool class manages and plays audio resources for applications.
这句就讲清楚了SoundPool的作用了:管理应用的音频资源。那么看下是怎么管理的。
在几个方法中我们关注其中的四个重载load()方法和一个play()方法。
load中加载声音资源的位置可以是File,path,Assets或者应用的资源中加载,play()方法中各个参数的说明如下,
英文意思还是比较简单的,实在不懂的可以百度查看,原谅我懒,没必要去给大家翻译下,原汁原味的意思更显高逼格。
2.开始撸代码。
大概看懂了API之后我们就来手撸代码了,请打开AS,新建项目………………
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button btn01 , btn02 , btn03 , btn04 ; private SoundPool soundPool ; List<Integer> soundIdList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); AudioAttributes audioAttributes = new AudioAttributes.Builder() // 设置场景 .setUsage(AudioAttributes.USAGE_NOTIFICATION ) // 设置类型 .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) .build(); soundPool = new SoundPool.Builder() // 设置上面的属性 .setAudioAttributes(audioAttributes) // 设置最多10个音频流文件 .setMaxStreams(10).build(); // 加载音频流到soundPool中去,并且用List存储起来 soundIdList.add(soundPool.load(this , R.raw.keypress_delete , 1)); soundIdList.add(soundPool.load(this , R.raw.keypress_invalid , 1)); soundIdList.add(soundPool.load(this , R.raw.keypress_return , 1)); soundIdList.add(soundPool.load(this , R.raw.keypress_spacebar , 1)); soundIdList.add(soundPool.load(this , R.raw.keypress_standard , 1)); } // 初始化界面控件,并设置点击事件监听 private void initView(){ btn01 = (Button) this.findViewById(R.id.button1); btn02 = (Button) this.findViewById(R.id.button2); btn03 = (Button) this.findViewById(R.id.button3); btn04 = (Button) this.findViewById(R.id.button4); btn01.setOnClickListener(this); btn02.setOnClickListener(this); btn03.setOnClickListener(this); btn04.setOnClickListener(this); } @Override public void onClick(View v) {// 随机播放声音 , 根据按钮的值,来随机播放声音 soundPool.play( soundIdList.get(v.getId() % 5) , 1 ,1 , 0 , 0 , 1);}}
代码啥的还是比较少的,注释也比较完整。
演示的界面也比较简单,根据点击不同的按钮播放不同的声音。声音资源文件放到了raw文件夹下
大家可以自行去网络上搜寻一些,.ogg格式的音频资源,然后制作有个性的按钮点击声音。好了,小知识点的记录就到这里了。