package com.tagmae.tsgame_erwang;

import java.io.IOException;

import com.tsgame.tsgame_niuniu.util.Settingutil;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;

public class MediaManager {
	private static MediaPlayer mPlayer;;
	private static boolean isPause; // 是否暂停

	public static void playSound(String filePathString,
			OnCompletionListener onCompletionListener) {
		if (mPlayer == null) {
			mPlayer = new MediaPlayer();
			// 保险起见，设置报错监听
			mPlayer.setOnErrorListener(new OnErrorListener() {

				@Override
				public boolean onError(MediaPlayer mp, int what, int extra) {
					try {
						mp.reset();// 重置 MediaPlayer 对象
					} catch (Exception e) {
						// TODO: handle exception
					}
					return false;
				}
			});
		} else {
			try {
			mPlayer.reset();// 重置 MediaPlayer 对象
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

		try {
			mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);// 指定流媒体的类型
			mPlayer.setOnCompletionListener(onCompletionListener);
			mPlayer.setDataSource(filePathString);

			if (!Settingutil.voicePlaying) {
				mPlayer.setVolume(0f, 0f);
			} else {
				mPlayer.setVolume(1.0f, 1.0f);
			}

			mPlayer.prepareAsync();// 异步缓存
			// mPlayer.prepare();
			mPlayer.setOnPreparedListener(new OnPreparedListener() {

				@Override
				public void onPrepared(MediaPlayer mp) {
					// TODO Auto-generated method stub
					mPlayer.start();
				}
			});

		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 停止函数
	public static void pause() {
		if (mPlayer != null && mPlayer.isPlaying()) {
			mPlayer.pause();
			isPause = true;
		}
	}

	// 继续
	public static void resume() {
		if (mPlayer != null && isPause) {
			mPlayer.start();
			isPause = false;
		}
	}

	// 销毁 释放资源
	public static void release() {
		if (mPlayer != null) {
			mPlayer.stop();
			mPlayer.release();
			mPlayer = null;
		}
	}
}
