Android Java 使用SoundPool 播放各种音效


import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.SparseArray;


/**
 * 点击声音类
 */
public class SoundManager {

    private static SoundManager mSoundManager;
    private SoundPool mSoundPool;
    private AudioManager mAudioManager;
    private SparseArray<Integer> mSoundPoolMap;
    public static final int maxSounds = 4;

    public static SoundManager getInstance(Context context) {
        if (mSoundManager == null) {
            mSoundManager = new SoundManager(context);
        }

        return mSoundManager;
    }

    public SoundManager(Context mContext) {
        mAudioManager = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE);
        mSoundPool = new SoundPool(maxSounds, AudioManager.STREAM_MUSIC, 0);

        mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                boolean loaded = true;
            }
        });

        mSoundPoolMap = new SparseArray<Integer>();
        mSoundPoolMap.put(0, mSoundPool.load(mContext, R.raw.click, 0));
        mSoundPoolMap.put(1, mSoundPool.load(mContext, R.raw.success, 1));
        mSoundPoolMap.put(2, mSoundPool.load(mContext, R.raw.change, 2));
        mSoundPoolMap.put(3, mSoundPool.load(mContext, R.raw.click_up, 3));
        mSoundPoolMap.put(4, mSoundPool.load(mContext, R.raw.click_down, 4));
    }

    public void playSound(int index) {
        int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume,
                1, 0, 1f);
    }

    public static void clear() {
        if (mSoundManager != null) {
            mSoundManager.mSoundPool = null;
            mSoundManager.mAudioManager = null;
            mSoundManager.mSoundPoolMap = null;
        }
        mSoundManager = null;
    }
}



//使用

SoundManager soundManagerr = new SoundManager(getContext());
soundManager.playSound(index);

留下评论