package com.mjsheng.myappstore.widget;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;

import com.mjsheng.myappstore.R;


public class Sound {

    private SoundPool mSoundPool;
    private AudioManager mAudioManager;
    private float mCurrVolume;
    private Context mContext;
    private int mSoundId;

    public Sound(Context context) {
        mContext = context;
        if (mContext == null) return;
        if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            builder.setMaxStreams(1);//传入音频数量
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);//设置音频流的合适的属性
            builder.setAudioAttributes(attrBuilder.build());//加载一个AudioAttributes
            mSoundPool = builder.build();
            mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        } else {
            mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
            mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        }
//        setCustomSound(R.raw.button_sound);
    }

    // 播放声音
    public void playSoundEffect() {
        if (mContext == null) return;
        mCurrVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
        if (mSoundId > 0) {
            mSoundPool.play(mSoundId, mCurrVolume, mCurrVolume, 0, 0, 1);
        } else {
            mAudioManager.playSoundEffect(AudioManager.FX_KEY_CLICK, mCurrVolume);
        }
    }

    //设置声音
    public void setCustomSound(int resId) {
        if (mContext == null) return;
        mSoundId = mSoundPool.load(mContext, resId, 1);
    }

}
