package com.tagmae.tsgame_erwang;

import java.io.IOException;

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 mediaplayer1 {
	private  MediaPlayer mp;

	private boolean ispause = false;

	public void play(String path, int loop,
			OnCompletionListener OncompletionListener) {

		if (mp == null) {
			mp = new MediaPlayer();
			mp.setOnErrorListener(new OnErrorListener() {
				@Override
				public boolean onError(MediaPlayer mp, int what, int extra) {
					// TODO Auto-generated method stub
					mp.reset();
					return false;
				}
			});
		} else {
			mp.reset();// 可以使播放器从Error状态中恢复过来，重新会到Idle状态

		}
		try {
			if (loop == 1) {
				mp.setAudioStreamType(AudioManager.STREAM_MUSIC);// 准备完成后才可以播放
				mp.setOnCompletionListener(OncompletionListener);
				mp.setDataSource(path);
				
				mp.prepareAsync();//异步缓存
				// mPlayer.prepare();
				mp.setOnPreparedListener(new OnPreparedListener() {

					@Override
					public void onPrepared(MediaPlayer mp) {
						// TODO Auto-generated method stub
						mp.start();
					}
				});
				mp.setLooping(true);// 循环播放

			} else if (loop < 0) {
				pause();

			} else {

				mp.setLooping(false);// 单曲
			}

		} 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();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// me.prepareAsync(); //异步缓冲
	}

	public void pause() {
		if (mp != null && mp.isPlaying()) {
			mp.pause();
			ispause = true;
		}
	}

	public void resume() {
		if (mp != null && ispause) {
			mp.start();
			ispause = false;
		}
	}

	public void release() {
		if (mp != null) {
			mp.stop();
			mp.release();
			mp = null;
		}
	}
}
