Android 添加按鈕點擊音效

最近項目中遇到的一個需求:點擊金幣,播放金幣掉落的聲音。實現方式如下:

1. 在res下新建raw,把資源文件coin_click.wav放進去
sybil052-20190723-163221.png
2. 建立單例類

代碼如下:

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.Builder().build();
        //加載音頻文件
        soundPool.load(context, R.raw.coin_click, 1);
    }

    public void play(int number) {
        Log.d(TAG, "number " + number);
        /**
         * 播放音頻
         * params說明:
         * //左耳道音量【0~1】
         * //右耳道音量【0~1】
         * //播放優先級【0表示最低優先級】
         * //循環模式【0表示循環一次,-1表示一直循環,其他表示數字+1表示當前數字對應的循環次數】
         * //播放速度【1是正常,范圍從0~2】
         */
        soundPool.play(number, 1, 1, 0, 0, 1);
    }
}
3. 具體使用

代碼如下:

private void initView() {
    soundInstance = SoundPoolUtil.getInstance(this);
    ...
    mCoinView.setOnCoinClickListener(new CoinView.CoinClickListener() {
            @Override
            public void coinClick(View v, CoinBean coinBean) {
                if(coinBean == null){
                    showDialog();
                    return;
                }
                final float x = v.getX();
                final float y = v.getY();
                // 播放音效
                soundInstance.play(1);
                // 請求接口
                stealVK(v, x, y, coinBean.getId());
                // 移除金幣
                Iterator<CoinBean> iterator = mCoinBeans.iterator();
                while (iterator.hasNext()) {
                    CoinBean c = iterator.next();
                    if (c.getId() == coinBean.getId()) {
                        iterator.remove();
                    }
                }
                // 展示新一輪金幣
                if(mCoinBeans.size() == 0 && allCoins.size() != 0){
                    index += 1;
                    maxCount -= 1;
                    if(allCoins.size() > index){
                        mCoinBeans.addAll(allCoins.get(index));
                        if(maxCount > mCoinBeans.size()){
                            mCoinView.setCoins(mCoinBeans, mCoinBeans.size());
                        }else {
                            mCoinView.setCoins(mCoinBeans, maxCount);
                        }
                    }
                }
                totalNum = FormateUtil.add(totalNum, coinBean.getNumber());
                NumAnim.startAnim(tvVkNum, Double.parseDouble(totalNum));
                addTextView(v, coinBean.getNumber());
            }
        });
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容