当前位置:K88软件开发文章中心编程语言APP编程Android01 → 文章内容

9.1 使用SoundPool播放音效(Duang~)

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-12 6:27:48

ckTrace(); } bindViews(); } private void bindViews() { btn_play1 = (Button) findViewById(R.id.btn_play1); btn_play2 = (Button) findViewById(R.id.btn_play2); btn_play3 = (Button) findViewById(R.id.btn_play3); btn_play4 = (Button) findViewById(R.id.btn_play4); btn_play5 = (Button) findViewById(R.id.btn_play5); btn_release = (Button) findViewById(R.id.btn_release); btn_play1.setOnClickListener(this); btn_play2.setOnClickListener(this); btn_play3.setOnClickListener(this); btn_play4.setOnClickListener(this); btn_play5.setOnClickListener(this); btn_release.setOnClickListener(this); } private void initSP() throws Exception{ //设置最多可容纳5个音频流,音频的品质为5 mSoundPool = new SoundPool(5, AudioManager.STREAM_SYSTEM, 5); soundID.put(1, mSoundPool.load(this, R.raw.duang, 1)); soundID.put(2 , mSoundPool.load(getAssets().openFd("biaobiao.mp3") , 1)); //需要捕获IO异常 soundID.put(3, mSoundPool.load(this, R.raw.duang, 1)); soundID.put(4, mSoundPool.load(this, R.raw.duang, 1)); soundID.put(5, mSoundPool.load(this, R.raw.duang, 1)); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.btn_play1: mSoundPool.play(soundID.get(1), 1, 1, 0, 0, 1); break; case R.id.btn_play2: mSoundPool.play(soundID.get(2), 1, 1, 0, 0, 1); break; case R.id.btn_play3: mSoundPool.play(soundID.get(3), 1, 1, 0, 0, 1); break; case R.id.btn_play4: mSoundPool.play(soundID.get(4), 1, 1, 0, 0, 1); break; case R.id.btn_play5: mSoundPool.play(soundID.get(5), 1, 1, 0, 0, 1); break; case R.id.btn_release: mSoundPool.release(); //回收SoundPool资源 break; } }}代码非常简单,另外如果你点击了最后一个按钮的话,SoundPool就会被释放,然后再其他按钮就不会Duang了哦~4.OnLoadCompleteListener监听声音文件是否加载完毕嗯,这个是临时想起的,写完在写另一篇的时候突然想起,用法也很简单,我们可以往上面的代码中添加OnLoadCompleteListener这个东东,然后重写onLoadComplete()方法,最后为SoundPool对象设置这个东东即可!mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() { @Override public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { Toast.makeText(MainActivity.this,"加特技准备完毕~",Toast.LENGTH_SHORT).show(); }});5.示例代码下载:SoundPoolDemo.zip本节小结:好的,本节给大家科普了一下Andorid多媒体的一些常识,以及教了大家如何为自己的APP添加音效,只需通过简单的SoundPool即可实现,还等什么,往你的应用加上这个玩意,让你的应用Duang起来啊~,配合Demo食用更佳~

上一页  [1] [2] 


9.1 使用SoundPool播放音效(Duang~)