package com.tagmae.tsgame_erwang;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Build;
import android.os.Handler;

@SuppressLint("NewApi")
public class SoundPoolUtils {
	private static SoundPool sp = null;// 声明一个SoundPool的引用
	private static SoundPool sp1 = null;// 声明一个SoundPool的引用
	static Map<String, Integer> map = new HashMap<String, Integer>();
	Handler hand = new Handler();
	List<String> list = new ArrayList<String>();
	private static int num = 0;// 声明一个SoundPool的引用


	// loop 是否循环 0不循环 -1循环
	public static void playSound(final String sound, final int loop) {
		if (sp == null) {
			if (Build.VERSION.SDK_INT >= 21) {
				SoundPool.Builder builder = new SoundPool.Builder();
				builder.setMaxStreams(10);// 传入音频数量
				// AudioAttributes是一个封装音频各种属性的方法
				AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
				attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);// 设置音频流的合适的属性
				builder.setAudioAttributes(attrBuilder.build());// 加载一个AudioAttributes
				sp = builder.build();
			} else {
				sp = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);// 创建SoundPool对象
			}
		}

		if (loop >= 0) {

			sp.load(sound, 1);

			sp.setOnLoadCompleteListener(new OnLoadCompleteListener() {

				@Override
				public void onLoadComplete(SoundPool soundPool, int sampleId,
						int status) {
					int currentStreamId;

			
					if (loop == 0) {
						currentStreamId = soundPool.play(sampleId, (float) 1,
								(float) 1, 1, 0, 1.0f);
						map.put(sound, currentStreamId);
						num++;
						if(num>80){
							num=0;
							dismisSoundPool();
						}
						String log = "playSound currentStreamId:"
								+ String.valueOf(currentStreamId);
						System.out.println(log);
					}

				}
			});

		} else if (loop < 0) {
			if (map.containsKey(sound)) {
				int streamID = map.get(sound);
				try {
					sp.pause(streamID);
				} catch (Exception e) {

				}

				// sp.release();

				// 暂停声音
			}

		}

	}

	/**
	 * @Title: dismisSoundPool @Description: 释放播放池 @param 设定文件 @return void 返回类型 @throws
	 */
	public static void dismisSoundPool() {
		if (sp != null) {
			try {
				sp.release();
				sp = null;
			} catch (Exception e) {
				// TODO: handle exception
			}
		
		}
	}
}
