//第一步 在res下新建raw,把资源文件放进去
//找点击音效这个网址上面有很多:点击音效下载_点击音效大全_站长素材
//第二步建立单例类:SoundPoolUtil
public class SoundPoolUtil {
private static SoundPoolUtil soundPoolUtil;
private SoundPool soundPool;
//单例模式
public static SoundPoolUtil getInstance(Context context) {
if (soundPoolUtil == null)
soundPoolUtil = new SoundPoolUtil(context);
return soundPoolUtil;
}
@SuppressLint("NewApi")//这里初始化SoundPool的方法是安卓5.0以后提供的新方式
private SoundPoolUtil(Context context) {
// soundPool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 0);
soundPool = new SoundPool.Builder().build();
//加载音频文件
soundPool.load(context, R.raw.click_music, 1);
}
public void play(int number) {
Log.d("tag", "number " + number);
//播放音频
soundPool.play(number, 1, 1, 0, 0, 1);
}
}
//第三步 在Activity里使用:
//先完成初始化,比如在initView()或者initData()方法里:
SoundPoolUtil instance = SoundPoolUtil.getInstance();
//然后再从按钮上调用:
instance.play(1);
//-----------------------------------------------------------------------完------------------------------------------------------------------------------