package com.backfire.doudizhu.common;

import java.io.IOException;

import net.yeeyo.doudizhu.feiyu.R;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;

import com.backfire.room.data.ConfigCenter;

public class PlayMedia {

	private MediaPlayer mediaPlayerBg = null;

	public PlayMedia(Context context) {

		mediaPlayerBg = MediaPlayer.create(context, R.raw.back_music);
		// 背景音乐循环播放
		mediaPlayerBg.setLooping(true);
		AudioManager mAudioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		float max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		float current = mAudioManager
				.getStreamVolume(AudioManager.STREAM_MUSIC);
		int bg_music = ShareData.getInstance().getIntValue("BG_MUSIC",
				(int) ((current / max) * 100f));
		mediaPlayerBg.setVolume(bg_music / 100f, bg_music / 100f);
	}

	/**
	 * 播放背景音乐
	 * 
	 * @param view
	 */
	public void startBgMusic() {
		if (mediaPlayerBg != null) {
			mediaPlayerBg.stop();
		}
		try {
			mediaPlayerBg.prepare();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (!ConfigCenter.volume_off && !mediaPlayerBg.isPlaying()) {
			mediaPlayerBg.start();
		}
	}

	/**
	 * 停止播放背景音乐
	 * 
	 * @param view
	 */
	public void stopBgMusic() {
		if (mediaPlayerBg != null && mediaPlayerBg.isPlaying())
			mediaPlayerBg.stop();
	}

	public void clear() {
		mediaPlayerBg = null;
	}

	public void setVolume(float volume) {
		mediaPlayerBg.setVolume(volume, volume);
	}
}