Android: I click on the button to play the sound - android

I'm creating piano app but I got problem when i click on the button to play many times i can't hear sound when i click on the button again. After i click on the button many times all the sounds are not heard how to solve this problem?
public class Music_piano extends Activity {
Button btn_s_ddo,btn_s_re,btn_s_mi,btn_s_fa,btn_s_so,btn_s_la,btn_s_si,btn_ldo;
MediaPlayer mp = new MediaPlayer();
MediaPlayer mp1,mp2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_music_piano);
}
public void btn_sound_ddo(View v){
mp = MediaPlayer.create(this, R.raw.ddo);
mp.start();
}
public void btn_sound_re(View v){
mp = MediaPlayer.create(this, R.raw.re);
mp.start();
}
public void btn_sound_mi(View v){
mp = MediaPlayer.create(this, R.raw.mi);
mp.start();
}
public void btn_sound_fa(View v){
mp = MediaPlayer.create(this, R.raw.fa);
mp.start();
}
public void btn_sound_so(View v){
mp = MediaPlayer.create(this, R.raw.sol);
mp.start();
}
public void btn_sound_la(View v){
mp = MediaPlayer.create(this, R.raw.la);
mp.start();
}
public void btn_sound_si(View v){
mp = MediaPlayer.create(this, R.raw.si);
mp.start();
}
public void btn_sound_ldo(View v){
mp = MediaPlayer.create(this, R.raw.ddo_last);
mp.start();
}
}

Can you please try below code ? I have tried it, worked well for me.
Button btnOne = (Button)findViewById(R.id.btnOne);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MediaPlayer mPlayer = MediaPlayer.create(TempActivity.this, R.raw.mysoundfile);
mPlayer.start();
}
});
Hope it will help you.

its better to create single instance of MediaPlayer and reuse it
MediaPlayer mMediaPlayer = new MediaPlayer(); // global variable
//write below code on buttons onclick method
AssetFileDescriptor assetFile = context.getAssets().openFd(audioFile);
mMediaPlayer.reset();
mMediaPlayer.setDataSource(assetFile.getFileDescriptor(),
assetFile.getStartOffset(), assetFile.getLength());
mMediaPlayer.prepare();
mMediaPlayer.start();
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});

I wrote a simple SoundManager class with a demo activity. No comment whatsoever as I think its pretty easy to read. Refer to SoundPool for details.
SoundManager class
package com.makeez.sfx;
import android.content.Context;
import android.media.SoundPool;
import java.util.HashMap;
import java.util.Map;
public class SoundManager {
private final Map<Integer, Integer> sfxId = new HashMap<>();
private SoundPool sfx;
public SoundManager(int maxStreams, int streamType, int srcQuality) {
sfx = new SoundPool(maxStreams, streamType, srcQuality);
}
public void load(Context context, int... resources) {
if (context == null) {
throw new NullPointerException("Context must not be null.");
}
if (resources == null) {
return;
}
for (int resource : resources) {
int soundId = sfx.load(context, resource, 1);
sfxId.put(resource, soundId);
}
}
public void play(int resId) {
Integer soundId = sfxId.get(resId);
if (soundId != null) {
sfx.play(soundId, 1.0f, 1.0f, 0, 0, 1.0f);
}
}
public void release() {
if (sfx != null) {
sfx.autoPause();
sfx.release();
sfx = null;
}
}
}
Demo activity
package com.makeez.sfx;
import android.media.AudioManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private SoundManager manager;
private int position = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager = new SoundManager(1, AudioManager.STREAM_MUSIC, 0);
manager.load(this, R.raw.sfx_0001, R.raw.sfx_0002, R.raw.sfx_0003, R.raw.sfx_0004, R.raw.sfx_0005);
Button button = (Button) findViewById(R.id.play);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (position) {
case 0: manager.play(R.raw.sfx_0001); break;
case 1: manager.play(R.raw.sfx_0002); break;
case 2: manager.play(R.raw.sfx_0003); break;
case 3: manager.play(R.raw.sfx_0004); break;
case 4: manager.play(R.raw.sfx_0005); break;
}
if (++position >= 5) {
position = 0;
}
}
});
}
#Override
protected void onDestroy() {
manager.release();
super.onDestroy();
}
}

Related

How can get timer from asynctask?

Cant access the time in AsyncTask, the variable point doesn't change anymore
Here is my code:
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class GamePlayActivity extends Activity {
ArrayList<Player> arrPlayer = new ArrayList<Player>();
TextView tvLevel, tvPoint;
ImageView ivGuessedImage;
Button btn1stChoice, btn2ndChoice, btn3rdChoice, btn4thChoice;
int level = 1;
int point = 0;
Random rand = new Random(System.currentTimeMillis());
ProgressBar customProgress;
TextView progressDisplay;
int myProgress;
MediaPlayer mp1, mp2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_gameplayactivity);
mp1 = MediaPlayer.create(GamePlayActivity.this, R.raw.uefa_champion_league);
mp2 = MediaPlayer.create(GamePlayActivity.this, R.raw.the_time_of_our_life);
mp1.start();
mp1.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp2.start();
}
});
mp2.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp1.start();
}
});
tvLevel = (TextView) findViewById(R.id.tvLevel);
tvPoint = (TextView) findViewById(R.id.tvPoint);
ivGuessedImage = (ImageView) findViewById(R.id.ivGuessedImage);
btn1stChoice = (Button) findViewById(R.id.btn1stChoice);
btn2ndChoice = (Button) findViewById(R.id.btn2ndChoice);
btn3rdChoice = (Button) findViewById(R.id.btn3rdChoice);
btn4thChoice = (Button) findViewById(R.id.btn4thChoice);
arrPlayer = createPlayer();
Collections.shuffle(arrPlayer);
int resID = getResources().getIdentifier(arrPlayer.get(0).getPlayerFile(), "drawable", getPackageName());
ivGuessedImage.setImageResource(resID);
btn1stChoice.setText(arrPlayer.get(0).getPlayerName());
btn2ndChoice.setText(arrPlayer.get(1).getPlayerName());
btn3rdChoice.setText(arrPlayer.get(2).getPlayerName());
btn4thChoice.setText(arrPlayer.get(3).getPlayerName());
customProgress = (ProgressBar)findViewById(R.id.customProgress);
progressDisplay = (TextView)findViewById(R.id.progressDisplay);
new ShowCustomProgressBarAsyncTask().execute();
if(myProgress < 1){
Intent intent = new Intent(GamePlayActivity.this, GameOverActivity.class);
startActivity(intent);
}
btn1stChoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btn1stChoice.getText().toString() == arrPlayer.get(0).getPlayerName()) {
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.right_answer);
mp.start();
point = point + 2;
tvPoint.setText(point + " Point");
createNewLevel();
myProgress = 100;
} else {
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.wrong_answer);
mp.start();
Intent intent = new Intent(GamePlayActivity.this, GameOverActivity.class);
intent.putExtra("Point", point);
startActivity(intent);
}
}
});
btn2ndChoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(btn2ndChoice.getText().toString() == arrPlayer.get(0).getPlayerName()){
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.right_answer);
mp.start();
point = point + 2;
tvPoint.setText(point + " Point");
createNewLevel();
myProgress = 100;
}
else{
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.wrong_answer);
mp.start();
Intent intent = new Intent(GamePlayActivity.this, GameOverActivity.class);
intent.putExtra("Point", point);
startActivity(intent);
}
}
});
btn3rdChoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(btn3rdChoice.getText().toString() == arrPlayer.get(0).getPlayerName()){
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.right_answer);
mp.start();
point = point + 2;
tvPoint.setText(point + " Point");
createNewLevel();
myProgress = 100;
}
else{
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.wrong_answer);
mp.start();
Intent intent = new Intent(GamePlayActivity.this, GameOverActivity.class);
intent.putExtra("Point", point);
startActivity(intent);
}
}
});
btn4thChoice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(btn4thChoice.getText().toString() == arrPlayer.get(0).getPlayerName()){
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.right_answer);
mp.start();
point = point + 2;
tvPoint.setText(point + " Point");
createNewLevel();
myProgress = 100;
}
else{
final MediaPlayer mp = MediaPlayer.create(GamePlayActivity.this, R.raw.wrong_answer);
mp.start();
Intent intent = new Intent(GamePlayActivity.this, GameOverActivity.class);
intent.putExtra("Point", point);
startActivity(intent);
}
}
});
}
public class ShowCustomProgressBarAsyncTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
myProgress = 100;
}
#Override
protected Void doInBackground(Void... params) {
while(myProgress>0){
myProgress--;
publishProgress(myProgress);
SystemClock.sleep(200);
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
customProgress.setProgress(values[0]);
customProgress.setSecondaryProgress(values[0] + 1);
progressDisplay.setText(String.valueOf(myProgress)+"%");
}
#Override
protected void onPostExecute(Void result) {
}
}
public void createNewLevel(){
arrPlayer.remove(0);
Collections.shuffle(arrPlayer);
int randomButtonChoice = rand.nextInt(4);
int resID = getResources().getIdentifier(arrPlayer.get(0).getPlayerFile(), "drawable", getPackageName());
((BitmapDrawable)ivGuessedImage.getDrawable()).getBitmap().recycle();
ivGuessedImage.setImageResource(resID);
switch (randomButtonChoice){
case 0: {
btn1stChoice.setText(arrPlayer.get(0).getPlayerName());
btn2ndChoice.setText(arrPlayer.get(1).getPlayerName());
btn3rdChoice.setText(arrPlayer.get(2).getPlayerName());
btn4thChoice.setText(arrPlayer.get(3).getPlayerName());
break;
}
case 1: {
btn1stChoice.setText(arrPlayer.get(1).getPlayerName());
btn2ndChoice.setText(arrPlayer.get(0).getPlayerName());
btn3rdChoice.setText(arrPlayer.get(2).getPlayerName());
btn4thChoice.setText(arrPlayer.get(3).getPlayerName());
break;
}
case 2: {
btn1stChoice.setText(arrPlayer.get(1).getPlayerName());
btn2ndChoice.setText(arrPlayer.get(2).getPlayerName());
btn3rdChoice.setText(arrPlayer.get(0).getPlayerName());
btn4thChoice.setText(arrPlayer.get(3).getPlayerName());
break;
}
case 3: {
btn1stChoice.setText(arrPlayer.get(1).getPlayerName());
btn2ndChoice.setText(arrPlayer.get(2).getPlayerName());
btn3rdChoice.setText(arrPlayer.get(3).getPlayerName());
btn4thChoice.setText(arrPlayer.get(0).getPlayerName());
break;
}
}
level++;
tvLevel.setText("Level " + level);
}
}
}
You could do that with an interface
create an interface in your AsyncTask, and create a method which will be used as the callback
public class ShowCustomProgressBarAsyncTask extends AsyncTask<Void, Integer, Void> {
interface ProgressListner {
public void onProgressChanged(int progress);
}
private ProgressListner listner;
public ShowCustomProgressBarAsyncTask(ProgressListner listner) {
this.listner = listner;
}
//..your remaining codes
#Override
protected void onProgressUpdate(Integer... values) {
//..your remaining codes
listner.onProgressChanged(values[0]);
}
}
Then implement that interface in your activity.
Also pass an instance of the interface through the constructor to the AsyncTask.
Then using that instance you can callback a method which will pass the progress value
public class GamePlayActivity extends Activity implements ProgressListner{
//.. your remaining codes
new ShowCustomProgressBarAsyncTask(this).execute();
public void onProgressChanged(int progress) {
a = progress;
}
}

Is this a good way to use MediaPlayer?

I think this is a decent way to use MediaPlayer for a Button or one time use. Am I right? Is the try block necessary? And what should I be trying to catch here? I'm really having a hard time finding a rock solid way to play a sound once.
// Button sound
private void playButtonSound() {
try{
final MediaPlayer startPlayer = MediaPlayer.create(
getApplicationContext(), R.raw.sound);
startPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
startPlayer.release();
}
});
startPlayer.start();
} catch(Throwable t){}
}
I use it like that:
public class PlayaudioActivity extends Activity {
private MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.tosse);
mp.start();
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}

My code won't run?

I am working with Fragments however this code wont run. can someone help me with this. The problem in the code seems to be with this part "(start.this,".
public class frag extends FragmentActivity {
public MediaPlayer mp = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mp == null) {
mp = MediaPlayer.create(start.this, R.raw.praise1);
mp.start();
}else {
mp.stop();
mp = null;
} }
});
}
}
Change your code to
public class frag extends FragmentActivity {
public MediaPlayer mp = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (mp == null) {
mp = MediaPlayer.create(getApplicationContext(), R.raw.praise1);//==> Here is the change
mp.start();
}else {
mp.stop();
mp = null;
} }
});
}
}
Change start.this to an actual context. You could use getParent() or you could store the context before creating the onClickListener and pass it in:
setContentView(R.layout.activity_main);
final Context context = this;
//inside the onClickListener
mp = MediaPlayer.create(context, R.raw.praise1);

How to create Button to control background sound.

I'm trying to add background music to my application. All I want is the sound should played on pressing the btnoptn Button and its text transitions into the "music off". The music should continue on any Activity until the settings page is returned to and the same Button is pressed again. The music then stops and the Button text changes to "music on".
This my code so far:
package hello.english;
import hello.english.R;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.media.MediaPlayer;
import android.os.Bundle;
public class welcome extends Activity implements OnClickListener{
private Button btnoptn;
private Button btnmenu;
public static MediaPlayer mp2;
private void btnoptn(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button testButton = (Button) findViewById(R.id.btnoptn);
testButton.setTag(1);
testButton.setText("Musik Of");
mp2=MediaPlayer.create(this, R.raw.guitar_music);
mp2.start();
mp2.setLooping(true);
testButton.setOnClickListener( new View.OnClickListener() {
public void onClick (View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
mp2.start();
mp2.setLooping(true);
testButton.setText("Musik Of");
v.setTag(0); //pause
} else {
mp2.pause();
testButton.setText("Musik On");
v.setTag(1);
} //pause
}
});
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome);
btnoptn=(Button)findViewById(R.id.btnoptn);
btnmenu=(Button)findViewById(R.id.btnmenu);
btnoptn.setOnClickListener( new View.OnClickListener() {
public void onClick(View view) {
btnoptn(null);
}
});
btnmenu.setOnClickListener( new View.OnClickListener() {
public void onClick(View view2) {
btnmenu();
}
});
}
protected void btnmenu() {
try {
Intent btnmenu= new Intent (this, menuenglish.class);
startActivity(btnmenu);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onStart() {
super.onStart();
btnoptn.setTag(0);
}
public void onClick(View view2) {
// TODO Auto-generated method stub
}
}
This is a really simple example. I don't know how it works if you switch between Activities, i never really worked with the MediaPlayer class.
public class MainActivity extends Activity
{
private MediaPlayer mediaPlayer;
private Button musicButton;
private OnClickListener listener = new OnClickListener()
{
// a boolean value in the names Onclicklistener class.
// this will help us to know, if the music is playing or not.
boolean isPlaying = false;
#Override
public void onClick(View arg0)
{
if(isPlaying)
{
mediaPlayer.pause(); //stop the music
musicButton.setText("Start"); //change the buttons text
}
else
{
mediaPlayer.start(); //start the music
musicButton.setText("Stop"); //change the text
}
//changing the boolean value
isPlaying = !isPlaying;
}
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Creating the mediaplayer with a desired soundtrack.
mediaPlayer = MediaPlayer.create(this, R.raw.my_music);
//Getting the Button reference from the xml
musicButton = (Button) findViewById(R.id.music_button);
//Setting the listener
musicButton.setOnClickListener(listener);
}
}

Android Media Player play/pause Button

In my project, I am playing music file in android media player by using the following code
MediaPlayer mPlayer = MediaPlayer.create(MyActivity.this, R.raw.myfile);
mPlayer.start();
the above is coded in the onclick of the play button.
I want to pause the playback by clicking the same button again.ie) single button for play/pause.
How shall i do this.
You could use simple if-check to handle the pausing. Try this:
if(mPlayer.isPlaying()){
mPlayer.pause();
} else {
mPlayer.start();
}
Please try this::
final Button bPlay = (Button) findViewById(R.id.bPlay);
MediaPlayer song1 = MediaPlayer.create(tutorialFour.this, R.raw.fluet);
Button bStop = (Button) findViewById(R.id.bStop);
bPlay.setWidth(10);
song1.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
bPlay.setText("Play");
}
});
bPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
b = true;
if (bPlay.getText().equals("Play") && b == true) {
song1.start();
bPlay.setText("Pause");
b = false;
} else if (bPlay.getText().equals("Pause")) {
x = song1.getCurrentPosition();
song1.pause();
bPlay.setText("Resume");
Log.v("log", "" + x);
b = false;
} else if (bPlay.getText().equals("Resume") && b == true) {
song1.seekTo(x);
song1.start();
bPlay.setText("Pause");
b = false;
}
}
});
Inside the button click check for mediaPlayer.isPlaying(). This will return true if the media player is playing else false.
So now with this, flag value you can make a if statement and switch to play or pause like this,
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if (mediaplayer.isPlaying()) {
mediaplayer.pause();
} else {
mediaplayer.start();
}
}
});
Below code takes care of your play/pause button click event along with forward and backward buttons for forward and backward seek on the seekbar provided (which is synchronized with the media track). Currently it plays just ONE song. However, you can add to that. This is my first media player using mediaplayer class, so you might find it a bit primitive. However if you need you can also check out the VideoView examples. It's apparently easier with VideoView as the standard media console is already present in the form of pre-defined widgets. so that makes designing the player much easier.
package in.org.Test;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.Toast;
public class Test12Activity extends Activity implements OnClickListener,Runnable {
private static final String isPlaying = "Media is Playing";
private static final String notPlaying = "Media has stopped Playing";
private SeekBar seek;
MediaPlayer player = new MediaPlayer();
private ImageButton plus,minus;
ImageButton im;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
plus = (ImageButton) findViewById(R.id.imageButton2);
minus = (ImageButton) findViewById(R.id.imageButton3);
player = MediaPlayer.create(this, R.raw.sound2);
player.setLooping(false);
im = (ImageButton) this.findViewById(R.id.imageButton1);
seek = (SeekBar) findViewById(R.id.seekBar1);
seek.setVisibility(ProgressBar.VISIBLE);
seek.setProgress(0);
seek.setMax(player.getDuration());
new Thread(this).start();
im.setOnClickListener(this);
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { int cu = player.getCurrentPosition(); player.seekTo(cu-5000); }});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {int cu = player.getCurrentPosition(); player.seekTo(cu+5000);}});
}
#Override
public void onClick(View arg0) {
if (arg0.getId() == R.id.imageButton1) {
if(player.isPlaying()) {
player.pause();
Toast.makeText(this, notPlaying, Toast.LENGTH_LONG).show();
ImageButton img1=(ImageButton) this.findViewById(R.id.imageButton1);
img1.setImageResource(R.drawable.play);
}
else
{
player.start();
Toast.makeText(this, isPlaying, Toast.LENGTH_LONG).show();
ImageButton img1=(ImageButton) this.findViewById(R.id.imageButton1);
img1.setImageResource(R.drawable.pause);
}
}
}
#Override
public void run() {
int currentPosition= 0; String s;
int total = player.getDuration();
while (player!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= player.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek.setProgress(currentPosition);
}
}
}
MediaPlayer mpE = MediaPlayer.create(GuitarTuner.this, R.raw.test2 );
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mpE.isPlaying()) {
mpE.pause();
play.setBackgroundResource(R.drawable.play);
} else {
mpE.start();
play.setBackgroundResource(R.drawable.pause);
}
}
});
For pausing the Mediaplayer:
Mediaplayer.pause();
length = Mediaplayer.getCurrentPosition();
and for resuming the player from the position where it stopped lately is done by:
Mediaplayer.seekTo(length);
Mediaplayer.start();
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//the song was previously saved in the raw folder. The name of the song is mylife (it's an mp3 file)
final MediaPlayer mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.mylife);
// Play song
Button playButton = (Button) findViewById(R.id.play);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.start(); // no need to call prepare(); create() does that for you
}
});
// Pause song
Button pauseButton = (Button) findViewById(R.id.pause);
pauseButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.pause();
}
});
// Stop song - when you stop a song, you can't play it again. First you need to prepare it.
Button stopButton = (Button) findViewById(R.id.stop);
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
mMediaPlayer.stop();
mMediaPlayer.prepareAsync();
}
});
}
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = button.getText().toString();
if (text.equals("play")){
mediaPlayer.start();
button.setText("pause"); //changing text
}
else if (text.equals("pause")){
mediaPlayer.pause();
button.setText("play"); //changing text
}
}
});
very simple solution. If mediaplayer is playing, display play button and pause the mediaplayer. If not playing, do the opposite.
playBtn.setOnClickListener(view -> {
//events on play buttons
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
playBtn.setImageResource(R.drawable.play);
} else {
mediaPlayer.pause();
playBtn.setImageResource(R.drawable.pause);
}
});

Categories

Resources