Get value of dice - java

I want make a Dice game, i have use a github project (https://github.com/dylanmtaylor/Simple-Dice).
The MainActivity is available here : https://github.com/dylanmtaylor/Simple-Dice/blob/master/src/com/dylantaylor/simpledice/RollDice.java
I want to get the value of the dice
Exemple :
If the first dice is 1 and the second is 6 we have a total of 7 i want make an action.
I have make a button who change a textview, this button try to get the number of the dices.
TextView hwTextView = (TextView)findViewById(R.id.textView8);
hwTextView.setText(String.valueOf(diceSum));
I have try to get the value "diceSum", "diceImages", "dice", "dice[roll[0]", "dice[roll[1]" but that didn't show a number.
How can i do try to get the value of the dice ?
My MainActivity
public class dices extends AppCompatActivity {
Button button;
private final int rollAnimations = 50;
private final int delayTime = 15;
private Resources res;
private final int[] diceImages = new int[] { R.drawable.d1, R.drawable.d2, R.drawable.d3, R.drawable.d4, R.drawable.d5, R.drawable.d6 };
private Drawable dice[] = new Drawable[6];
private final Random randomGen = new Random();
#SuppressWarnings("unused")
private int diceSum;
private int roll[] = new int[] { 6, 6 };
private ImageView die1;
private ImageView die2;
private LinearLayout diceContainer;
private SensorManager sensorMgr;
private Handler animationHandler;
private long lastUpdate = -1;
private float x, y, z;
private float last_x, last_y, last_z;
private boolean paused = false;
private static final int UPDATE_DELAY = 50;
private static final int SHAKE_THRESHOLD = 800;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
paused = false;
setContentView(R.layout.activity_dixit);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setStatusBarColor(Color.parseColor("#2c3e50"));
}
View view = this.getWindow().getDecorView();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
button=(Button)findViewById(R.id.button_roll);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollDice();
TextView hwTextView = (TextView)findViewById(R.id.textView8);
hwTextView.setText(String.valueOf(diceSum));
}
});
res = getResources();
for (int i = 0; i < 6; i++) {
dice[i] = res.getDrawable(diceImages[i]);
}
die1 = (ImageView) findViewById(R.id.die1);
die2 = (ImageView) findViewById(R.id.die2);
animationHandler = new Handler() {
public void handleMessage(Message msg) {
die1.setImageDrawable(dice[roll[0]]);
die2.setImageDrawable(dice[roll[1]]);
}
};
}
private void rollDice() {
if (paused) return;
new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < rollAnimations; i++) {
doRoll();
}
}
}).start();
MediaPlayer mp = MediaPlayer.create(this, R.raw.roll);
try {
mp.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
private void doRoll() { // only does a single roll
roll[0] = randomGen.nextInt(6);
roll[1] = randomGen.nextInt(6);
diceSum = roll[0] + roll[1] + 2; // 2 is added because the values of the rolls start with 0 not 1
synchronized (getLayoutInflater()) {
animationHandler.sendEmptyMessage(0);
}
try { // delay to alloy for smooth animation
Thread.sleep(delayTime);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
public void onResume() {
super.onResume();
paused = false;
}
public void onPause() {
super.onPause();
paused = true;
}
}

I didn't understand why your code didn't work. I myself making a very small games based on "Scarne's dice game(pig)" and myself facing the challenge of retrieving the value of dice rolled. Mind, I am just using one die. This is what I did:
int userScore;
private int[] diceArray = {R.drawable.d1, R.drawable.d2, R.drawable.d3,
R.drawable.d4,R.drawable.d5,R.drawable.d6};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRollBtnClicked() {
ImageView diceFace = (ImageView) findViewById(R.id.diceFaceImageView);
userScore = randomIntegerGenerator(1,6); // this is what you need
diceFace.setImageResource(diceArray[userScore]);
}
// function to return random integer from min to max
public int randomIntegerGenerator(int min, int max) {
return random.nextInt((max - min) + 1) + min;
}
I am storing my rolled die value in userScore. You can use the similar approach.

Related

Product Subtract Button is not working perfectly in ecommerce app

I am facing issue while subtracting my product, I am using three buttons to get the value of the selected one and then multiply these value for add more product or subtract . But when i click on subtract button it will minus the whole amount. So please help me in this. Below mention is my code. If you want some more info then please ask me.
public class ShowDetailActivity extends AppCompatActivity {
private TextView addToCardBtn;
private TextView titleTxt, feeTxt, descriptionTxt, numberOrderTxt;
private ImageView plusBtn, minusBtn, picFood, priceBtn, mediumPriceBtn, largePriceBtn;
private ProductsDomain object;
private int numberOrder = 1;
private ManagementCart managementCart;
private LinearLayout cheese_ll;
private LinearLayout scale_ll;
private int itemPrice;
private CheckBox cheeseBoxyes;
private int price;
private int checkvalue;
private int uncheckValue;
private boolean cheeseBoolean = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_detail);
managementCart = new ManagementCart(this);
initView();
getBundle();
//Button Code
price=object.getPrice();
priceBtn.setOnClickListener(this::onClick);
mediumPriceBtn.setOnClickListener(this::onClick);
largePriceBtn.setOnClickListener(this::onClick);
//check box code for extra cheese
}
private void onClick(View view) {
int id=view.getId();
switch (id){
case R.id.smallPriceBtn:
price=object.getPrice();
itemPrice=object.getPrice();
feeTxt.setText(Integer.toString(price*numberOrder));
break;
case R.id.mediumPriceBtn:
price = object.getMediumPrice();
feeTxt.setText(Integer.toString(price*numberOrder));
itemPrice=object.getMediumPrice();
break;
case R.id.largePriceBtn:
price = object.getLargePrice();
feeTxt.setText(Integer.toString(price*numberOrder));
itemPrice=object.getLargePrice();
break;
}
}
private void getBundle() {
object = (ProductsDomain) getIntent().getSerializableExtra("object");
if (object.getWithCheese() == 1)//get cheese
{
cheese_ll.setVisibility(View.VISIBLE);
scale_ll.setVisibility(View.GONE);
} else {
cheese_ll.setVisibility(View.GONE);
scale_ll.setVisibility(View.VISIBLE);
}
Glide.with(this).load("http://192.168.100.215/pizzaVill/Images/" + object.getImage()).into(picFood);
titleTxt.setText(object.getName());
descriptionTxt.setText(object.getDescription());
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(object.getPrice()));
plusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numberOrder = numberOrder + 1;
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(numberOrder * price));
//Code if there is no size required
}
});
minusBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (numberOrder > 1) {
numberOrder = numberOrder - 1;
}
numberOrderTxt.setText(Integer.toString(numberOrder));
feeTxt.setText(Integer.toString(price - itemPrice));
}
});
addToCardBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
object.setNumberInCard(numberOrder);
object.setFinalPrice(price);
managementCart.insertFood(object);
}
});
}
private void initView() {
addToCardBtn = findViewById(R.id.addToCardBtn);
titleTxt = findViewById(R.id.titleTxt);
feeTxt = findViewById(R.id.priceTxt);
descriptionTxt = findViewById(R.id.descriptionTxt);
numberOrderTxt = findViewById(R.id.numberOrderTxt);
plusBtn = findViewById(R.id.plusBtn);
minusBtn = findViewById(R.id.minusBtn);
picFood = findViewById(R.id.foodPic);
priceBtn = findViewById(R.id.smallPriceBtn);
mediumPriceBtn = findViewById(R.id.mediumPriceBtn);
largePriceBtn = findViewById(R.id.largePriceBtn);
cheese_ll = findViewById(R.id.cheese_ll);
scale_ll = findViewById(R.id.scale_ll);
cheeseBoxyes = findViewById(R.id.cheeseBoxyes);
}

Increase animation speed when using Clipdrawable in Android studio?

From this thread: How to Customize a Progress Bar In Android
I made my own progress bar using ClipDrawAble animation and it works perfecty, and the code is here:
public class MainActivity extends AppCompatActivity {
private EditText etPercent;
private ClipDrawable mImageDrawable;
private Button fly_to_50;
// a field in your class
private int mLevel = 0;
private int fromLevel = 0;
private int toLevel = 0;
//public static final int MAX_LEVEL = 10000;
public static final int MAX_LEVEL = 10000;
public static final int LEVEL_DIFF = 100;
public static final int DELAY = 0;
public static final int START_AT_50 = 50;
private Handler mUpHandler = new Handler();
private Runnable animateUpImage = new Runnable() {
#Override
public void run() {
doTheUpAnimation(fromLevel, toLevel);
}
};
private Handler mDownHandler = new Handler();
private Runnable animateDownImage = new Runnable() {
#Override
public void run() {
doTheDownAnimation(fromLevel, toLevel);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etPercent = (EditText) findViewById(R.id.etPercent);
ImageView img = (ImageView) findViewById(R.id.imageView1);
mImageDrawable = (ClipDrawable) img.getDrawable();
mImageDrawable.setLevel(0);
}
private void doTheUpAnimation(int fromLevel, int toLevel) {
mLevel += LEVEL_DIFF;
mImageDrawable.setLevel(mLevel);
if (mLevel <= toLevel) {
mUpHandler.postDelayed(animateUpImage, DELAY);
} else {
mUpHandler.removeCallbacks(animateUpImage);
MainActivity.this.fromLevel = toLevel;
}
}
private void doTheDownAnimation(int fromLevel, int toLevel) {
mLevel -= LEVEL_DIFF;
mImageDrawable.setLevel(mLevel);
if (mLevel >= toLevel) {
mDownHandler.postDelayed(animateDownImage, DELAY);
} else {
mDownHandler.removeCallbacks(animateDownImage);
MainActivity.this.fromLevel = toLevel;
}
}
public void onClick50(View v){
mImageDrawable.setLevel(START_AT_50);
}
public void onClickOk(View v) {
//int temp_level = ((Integer.parseInt(etPercent.getText().toString())) * MAX_LEVEL) / 100;
int temp_level = ((Integer.parseInt(etPercent.getText().toString())) * MAX_LEVEL) / 100;
if (toLevel == temp_level || temp_level > MAX_LEVEL) {
return;
}
toLevel = (temp_level <= MAX_LEVEL) ? temp_level : toLevel;
if (toLevel > fromLevel) {
// cancel previous process first
mDownHandler.removeCallbacks(animateDownImage);
MainActivity.this.fromLevel = toLevel;
mUpHandler.post(animateUpImage);
} else {
// cancel previous process first
mUpHandler.removeCallbacks(animateUpImage);
MainActivity.this.fromLevel = toLevel;
mDownHandler.post(animateDownImage);
}
}
}
I set my "DELAY" variable to be 0, which increased the speed a little bit, however, I am not completely satisfied with the speed and would love to increase the speed more. Is this somehow possible? And if not, is there a chance that I can create a normal progress(would work here for sure), but using my own custom edited images?
Appreciate all answers!
Thank you.
SOLVED:
I changed this line:
mDownHandler.postDelayed(animateDownImage, DELAY);
with this:
mDownHandler.postAtTime(animateDownImage,DELAY);

Monitoring Voice in my android app

Iam making an android app which monitor voice in which when the voice loudness exceed a user defined threshold the app dial a specific number .
i done making voice monitoring and compared the highest value with the threshold then dialling the number .everything goes right except when the app returned after the call i find the monitoring isnt right , as the mic sensitivity is very week (measurement is very low ) i have to restart the app to obtain the right measurement , the second question here i make the comparison of the threshold and the last value of sound in the handler at the bottom , is this the right way ? thanks in advanceThis is the App image
Below is The Main activity
public class MainActivity extends AppCompatActivity {
private static final int sampleRate = 11025;
private static final int bufferSizeFactor = 10;
private Button Stop;
private ProgressBar On;
private Button Start;
private AudioRecord audio;
private int bufferSize;
private ProgressBar level;
private TextView textView;
volatile int threshold;
TextView testtextview;
private boolean clicked ;
private Handler handler = new Handler();
private int lastLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
threshold = 20000;
//progressbar detect voice
level = (ProgressBar) findViewById(R.id.progressbar_level);
level.setMax(32676);
//text displaying progress par value
textView = (TextView) findViewById(R.id.textView1);
testtextview = (TextView) findViewById(R.id.textViewtest);
if (audio != null) {
audio.stop();
audio.release();
audio = null;
handler.removeCallbacks(update);
} else {
bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT) * bufferSizeFactor;
audio = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
audio.startRecording();
Thread thread = new Thread(new Runnable() {
public void run() {
readAudioBuffer();
}
});
thread.setPriority(Thread.currentThread().getThreadGroup().getMaxPriority());
thread.start();
handler.removeCallbacks(update);
handler.postDelayed(update, 25);
}
//seekbar let user choose threshhold
SeekBar mSeekBar = (SeekBar) findViewById(R.id.seekBar);
//text displayin user choice
final TextView textViewuser = (TextView) findViewById(R.id.textView3);
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
textViewuser.setText("" + i + "/32676");
threshold = i ;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Stop = (Button) findViewById(R.id.dummy_buttonstop);
On = (ProgressBar) findViewById(R.id.progressBar11);
Start = (Button) findViewById(R.id.dummy_button);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Start.setVisibility(View.GONE);
On.setVisibility(View.VISIBLE);
clicked = true;
}
});
Stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Start.setVisibility(View.VISIBLE);
On.setVisibility(View.GONE);
clicked = false;
}
});
}
private void readAudioBuffer() {
try {
short[] buffer = new short[bufferSize];
int bufferReadResult;
do {
bufferReadResult = audio.read(buffer, 0, bufferSize);
for (int i = 0; i < bufferReadResult; i++) {
if (buffer[i] > lastLevel) {
lastLevel = buffer[i];
}
}
}
while (bufferReadResult > 0 && audio.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING);
if (audio != null) {
audio.release();
audio = null;
handler.removeCallbacks(update);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private Runnable update = new Runnable() {
public void run() {
MainActivity.this.level.setProgress(lastLevel);
textView.setText(lastLevel + "/" + level.getMax());
if (clicked) {
if (lastLevel > threshold) {
clicked=false;
Start.setVisibility(View.VISIBLE);
On.setVisibility(View.GONE);
String url = "tel:01224271138";
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
//recreate();
}
}
lastLevel *= .5;
handler.postAtTime(this, SystemClock.uptimeMillis() + 500);
}
};

App crashing when using SharedPreferences to carry over final score

My android app is crashing when using SharedPreferences to try and carry the final score over from when the game ends. The app crashes inside the onTouchEvent at the line.
SharedPreferences.Editor editor = mySharedPreferences.edit();
The idea is when the game ends it final score that is within the SVGameView to carry over into the SVGameOver class and display there. If anyone could give some advice that would be great!
SVGameView:
public class SVGameView extends SurfaceView implements Runnable {
private SurfaceHolder holder;
Thread thread = null;
volatile boolean running = false;
static final long FPS = 30;
private Sprite sprite;
private long lastClick;
private Bitmap ball, gameOver;
//private int x = 200, y = 200;
private int scorePosX = 100;
private int scorePosY = 100;
private int countScore = 0;
private int life = 1;
SharedPreferences mySharedPreferences;
public SVGameView(Context context) {
super(context);
thread = new Thread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
running = false;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
running = true;
thread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
ball = BitmapFactory.decodeResource(getResources(), R.drawable.ball2);
gameOver = BitmapFactory.decodeResource(getResources(),R.drawable.endscreen);
sprite = new Sprite(this, ball);
context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);
}
#Override
public void run() {
long ticksPS = 1000 / FPS;
long startTime;
long sleepTime;
while (running) {
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = getHolder().lockCanvas();
synchronized (getHolder()) {
update();
onDraw(c);
}
} finally {
if (c != null) {
getHolder().unlockCanvasAndPost(c);
}
}
sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
thread.sleep(sleepTime);
else
thread.sleep(10);
} catch (Exception e) {}
}
}
private void update(){
sprite.update();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
Paint paint = new Paint();
canvas.drawPaint(paint);
paint.setColor(Color.WHITE);
paint.setTextSize(48);
canvas.drawText("Score: " + countScore, scorePosX, scorePosY, paint);
canvas.drawText("Lives: " + life, 500, 100, paint);
sprite.onDraw(canvas);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if(System.currentTimeMillis()-lastClick > 300){
lastClick = System.currentTimeMillis();
}
synchronized (getHolder()){
if(sprite.isHit(event.getX(), event.getY())){
countScore += 1;
sprite.increase();
}else{
life --;
}
}
if(life == 0) {
getContext().startActivity(new Intent(getContext(), SVGameOver.class));
//Intent intent;
//intent = new Intent(getContext(), SVGameView.class);
//intent.putExtra("scoreOutput", countScore);
//Crashes Here
SharedPreferences.Editor editor = mySharedPreferences.edit();
editor.putString("cScore", String.valueOf(countScore));
}
return super.onTouchEvent(event);
}
}
SVGameOver Class:
public class SVGameOver extends Activity implements View.OnClickListener{
Button btnBack;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(this);
SharedPreferences mySharedPreferences = getSharedPreferences("myPrefsFile", 0);
String theScore = mySharedPreferences.getString("cScore","");
TextView textView = (TextView)findViewById(R.id.scoreOutput);
textView.setText(theScore);
//intent = getIntent();
//String uir = intent.getStringExtra("scoreOutput");
}
#Override
public void onClick(View v) {
}
}
XML Layout:
https://gyazo.com/8e49d02c66dde7ff0e7f09a4fa9eacd2
You're missing:
mySharedPreferences = context.getSharedPreferences("myPrefsFile", Context.MODE_PRIVATE);
in your SVGameView, so mySharedPreferences always null.
You missed assigning SharedPreferencesobject to your reference mySharedPreferences in SVGameView(Context context) -
context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);
Change it to
mySharedPreferences = context.getSharedPreferences("myPrefsFile",Context.MODE_PRIVATE);
You are not initializing the SharedPreference object right.
Use this library, which simplifies the use of SharedPreferences and will make life simpler for you.
Android-SharedPreferences-Helper simplifies usage of the default Android SharedPreferences Class. The developer can do in a few lines
of code which otherwise would have required several. Simple to
understand as compared to the default class and easy to use.

Create stream from audio file in Android

The use case is this, in Android (above Kit Kat): open a stream from an audio file, get its properties, modify the memory buffer and play the result.
I would like to know how to 1) properly create the stream from the audio file; 2) get its properties (channels, encoding, length) like for the javax.sound.sampled.AudioFormat, but using methods from the android.media framework.
I know how to build a stream from binary, add audio properties to it then playing it. I would like to do the other way and extract these properties (channels, encoding) from the existing sound file header, using latest classes of the Android framework.
Thanks!
Here is full streaming class use this :
public class MainActivity extends Activity implements OnClickListener,
OnTouchListener, OnCompletionListener, OnBufferingUpdateListener {
private Button btn_play, btn_pause, btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://songspkcompilations.com/indian/soulfularijit/%5BSongs.PK%5D%2012%20-%20Mickey%20Virus%20-%20Tose%20Naina.mp3";
private static final int MINUTES_IN_AN_HOUR = 60;
private static final int SECONDS_IN_A_MINUTE = 60;
private final Handler handler = new Handler();
private boolean is_loading = true;
private boolean is_stopped = false;
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
private TextView txtTime;
private ProgressBar musicProgress;
private ImageView artistImg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize_Controls();
}
private void initialize_Controls() {
btn_play = (Button) findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button) findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button) findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
musicProgress = (ProgressBar) findViewById(R.id.progress);
artistImg = (ImageView) findViewById(R.id.artistImg);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
txtTime = (TextView) findViewById(R.id.time);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar) v;
mediaPlayer
.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress());
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
// Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
if (is_stopped) {
is_stopped = false;
mediaPlayer.seekTo(0);
}
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
if (is_loading) {
is_loading = false;
musicProgress.setVisibility(View.GONE);
artistImg.setVisibility(View.VISIBLE);
}
int progress = (int) (((float) mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100);
int remainSec = (lengthOfAudio - mediaPlayer.getCurrentPosition()) / 1000;
seekBar.setProgress(progress);
txtTime.setText("" + timeConversion(remainSec));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
if (mediaPlayer != null) {
mediaPlayer.pause();
is_stopped = true;
}
seekBar.setProgress(0);
seekBar.setSecondaryProgress(0);
txtTime.setText("" + timeConversion(lengthOfAudio / 1000));
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
private void pauseAudio() {
if (mediaPlayer != null) {
mediaPlayer.pause();
}
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
if (mediaPlayer != null) {
mediaPlayer.start();
}
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
private static String timeConversion(int totalSeconds) {
int hours = totalSeconds / MINUTES_IN_AN_HOUR / SECONDS_IN_A_MINUTE;
int minutes = (totalSeconds - (hoursToSeconds(hours)))
/ SECONDS_IN_A_MINUTE;
int seconds = totalSeconds
- ((hoursToSeconds(hours)) + (minutesToSeconds(minutes)));
return hours + ":" + minutes + ":" + seconds;
}
private static int hoursToSeconds(int hours) {
return hours * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE;
}
private static int minutesToSeconds(int minutes) {
return minutes * SECONDS_IN_A_MINUTE;
}
class PlayTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
// Log.e("Error", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
playAudio();
updateSeekProgress();
}
}
#Override
protected void onResume() {
super.onResume();
new PlayTask().execute();
}
#Override
public void onBackPressed() {
super.onBackPressed();
pauseAudio();
finish();
}
}

Categories