package com.wdkl.app.ncs.callingbed.helper;

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

import com.wdkl.app.ncs.callingbed.R;

import java.util.HashMap;

public class SoundPoolHelper {

    private static SoundPoolHelper instance;
    private SoundPool soundPool;
    private HashMap<Integer, Integer> soundID = new HashMap<Integer, Integer>();
    private boolean isLoaded = false;

    public static SoundPoolHelper getInstance() {
        if (instance == null) {
            instance = new SoundPoolHelper();
        }
        return instance;
    }

    public void init(Context context) {
        if(Build.VERSION.SDK_INT > 21){
            SoundPool.Builder builder = new SoundPool.Builder();
            //传入音频数量
            builder.setMaxStreams(3);
            //AudioAttributes是一个封装音频各种属性的方法
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            //设置音频流的合适的属性
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_SYSTEM);//STREAM_MUSIC
            //加载一个AudioAttributes
            builder.setAudioAttributes(attrBuilder.build());
            soundPool = builder.build();
        }else{
            soundPool = new SoundPool(3, AudioManager.STREAM_SYSTEM, 0);
        }

        //来电
        soundID.put(1, soundPool.load(context, R.raw.incoming_call, 1));
        //去电
        soundID.put(2, soundPool.load(context, R.raw.outgoing_call, 1));
        //测试音频
        soundID.put(3, soundPool.load(context, R.raw.speaker_test, 1));
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                isLoaded = true;
            }
        });
    }

    public void playSound(int index) {
        try {
            if (isLoaded) {
                soundPool.play(soundID.get(index), 1, 1, 0, 0, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void release() {
        soundPool.release();
    }
}
