ProgressBar does not reset after audio is finished done - android

I have asked this question 2 times now still haven't got it to work. Any help would be awesome
My ProgressBar does not reset after audio is done, the bar just stays to the max blue line. I ask a question before on this and got it working but now just stopped working and not sure why it doesn't. Any help would be awesome.
All I want is it to chose a audio at random then play one and when finished you can press play again to listen to the same audio it chose at random.
Heres code:
public class player2 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_2);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound04; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound05; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound06;
// Listeners
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player2.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(100);
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if(mp.isPlaying()){
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}}});
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<=total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if(mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed(){
if (mp != null){
if(mp.isPlaying())
mp.stop();
mp.release();
}
//there is no reason to call super.finish(); here
//call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}

I did not check all the code thoroughly, but at a quick glance I would guess that your thread (which updates the progress bar) is stopping at completion and you never start it again (ie. when the user clicks play again). Just try restarting the thread in your pauseicon.setOnClickListener (when playback is complete). Example:
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mp.isPlaying()) {
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
// RESTART THE UPDATE THREAD //
new Thread(this).start();
}
}
});
EDIT using a static variable to store thread so that it can be restarted from the view's onClick method:
// add this to your class as a member
static Thread progressThread = new Thread(this);
// add this to BOTH onCreate and onClick
progressThread.start();
If this does not work (I can't test it out right now), you can simply keep the thread running, for example:
// flag to set when thread should be actively running
static boolean runThread = true;
// change your run method to something as follows
public void run() {
while ( runThread ) {
if ( mp != null && currentPosition <= total ) {
int currentPosition= 0;
int total = mp.getDuration();
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
else
Thread.sleep(1000);
}
}
// then when you no longer need to update the progress bar set the flag to false,
// which will cause your thread to finish. this can go anywhere, depending on
// your needs
runThread = false;

Related

android set seekbar to initial and toggle play button to pause when music finish

i am designing a mediaplayer from scratch so what i am getting stuck in is that when the song finish to play i want to set seekbar to initial value
i know this can be done with
seekBar.setProgress(0)
but this don't work with me and i want the play button to switch back to pause button and if the user play song again than the song will be played normally
here is my code of media player and hope you tell me what is the logic and how to place it
public class MusicPlayerActivity extends AppCompatActivity implements Runnable,
SeekBar.OnSeekBarChangeListener {
ImageView playpause;
SeekBar seekBar;
MediaPlayer mp = null;
int len = 0;
boolean isPlaying = false;
public MusicPlayerActivity() throws IOException {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
String url = getIntent().getExtras().getString("musicurl");
playpause = (ImageView)findViewById(R.id.imageView);
seekBar = (SeekBar)findViewById(R.id.seekBar);
playpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!isPlaying){
playpause.setImageResource(R.drawable.pause);
mp.pause();
len = mp.getCurrentPosition();
seekBar.setEnabled(false);
}else{
playpause.setImageResource(R.drawable.play);
mp.seekTo(len);
mp.start();
seekBar.setEnabled(true);
}
isPlaying = !isPlaying;
}
});
mp = new MediaPlayer();
try {
mp.setDataSource(url);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
//if(mp.isPlaying()) mp.stop(); mp.release();
mp.start();
seekBar.setMax(mp.getDuration());
new Thread(this).start();
// Toast.makeText(this, mp.getDuration(), Toast.LENGTH_SHORT).show();
}
//if(mp.isPlaying()){}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
try {
if (mp.isPlaying() || mp != null) {
if (fromUser)
mp.seekTo(progress);
} else if (mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void run() {
int currentPosition = mp.getCurrentPosition();
int total = mp.getDuration();
while (mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mp.stop();
startActivity(new Intent(this,MainActivity.class));
break;
}
return true;
}
#Override
public void onBackPressed() {
Intent mainActivity = new Intent(Intent.ACTION_MAIN);
mainActivity.addCategory(Intent.CATEGORY_HOME);
mainActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(mainActivity);
}
}
You are not setting the listener : seekbar.setOnSeekBarChangeListener(this)
Add seekbar.setOnSeekBarChangeListener(this); in your onCreate otherwise the onProgressChanged() does not get called.
To reset progress bar look into the following approach:
Set OnCompletionListener on your media player instance. When the media file completes playing, your can carry out the required actions in OnCompletion(MediaPlayer mp) callback function.
Adding following code snippet before mp.start() should work for you.
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
seekBar.setProgress(0); // sets seekbar to initial position.
toggleViews();//implement this function to toggle your play/pause button
}
});

Want MediaPlayer to continue running when screen is locked

How could I make it so that my MediaPlayer continues to play even when the phone is locked and the screen is off, thinking it may have to do something of making it a service but not sure. If so how could I go about changing it to a service or is there a quicker easier fix?
Any help would be great!
Here is code:
public class player2 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_2);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound04; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound05; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound06;
// Listeners
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player2.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if(mp.isPlaying()){
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}}});
}
static boolean runThread = true;
public void run() {
while ( runThread ) {
int currentPosition=0;
int total = mp.getDuration();
if ( mp != null && currentPosition <= total ) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
} else
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
runThread = false;
}
#Override
protected void onStop() {
super.onStop();
if (mp != null && mp.isPlaying()){
mp.pause();
}
}
#Override
public void onResume()
{
super.onResume();
if (mp != null){
if(!mp.isPlaying())
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Follow my tutorial below...In following tutorial i have stored .mp3 file in raw folder. if you have stored it in sd card and dynamically fetching that file then put its path in bundle and send it through intent which you can get in onStartCommand() method of your service.
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
Button startPlaybackButton, stopPlaybackButton;
Intent playbackServiceIntent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startPlaybackButton = (Button) this.findViewById(R.id.StartPlaybackButton);
stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);
startPlaybackButton.setOnClickListener(this);
stopPlaybackButton.setOnClickListener(this);
playbackServiceIntent = new Intent(this, BackgroundAudioService.class);
}
public void onClick(View v) {
if (v == startPlaybackButton) {
startService(playbackServiceIntent);
finish();
} else if (v == stopPlaybackButton) {
stopService(playbackServiceIntent);
finish();
}
}
}
BackgroundAudioService.java
public class BackgroundAudioService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
mediaPlayer = MediaPlayer.create(this, R.raw.abc);// YOUR FILE NAME
mediaPlayer.setOnCompletionListener(this);
Log.v("TEST", "1");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
Log.v("TEST", "2");
mediaPlayer.start();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Background Audio Player"
/>
<Button android:text="Start Playback" android:id="#+id/StartPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Stop Playback" android:id="#+id/StopPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
Don't forget to declare Service in manifest.xml like below,
<service android:name="com.demo.tute.BackgroundAudioService" />

ProgressBar does not reset after audio is finished

My ProgressBar does not reset after audio is done. I ask a question before on this and got it working but now just stopped working and not sure why it doesn't. Any help would be awesome.
All I want is it to chose a audio at random then play one and when finished you can press play again to listen to the same audio it chose at random.
Heres code:
public class player1 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound01; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound02; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound03;
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player1.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
//When audio is done will change pause to play
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if(mp.isPlaying()){
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}}});
}
//To update progress bar
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<=total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if (mp != null)
if(mp.isPlaying())
mp.stop();
mp.release();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed(){
if (mp != null){
if(mp.isPlaying())
mp.stop();
mp.release();
}
//there is no reason to call super.finish(); here
//call super.onBackPressed(); and it will finish that activity for you
super.onBackPressed();
}
}
You problem is mp.getDuration() is a milliseconds, which changes in each song. So don't use progressBar.setMax(mp.getDuration());. As it only works once for the very first song. Use progressBar.setMax(100); instead. Then use currentPosition= 100 * mp.getCurrentPosition() / mp.getDuration(); This should work fine.
Also don't forget adding progressBar.setProgress(0); when one song is finished or stop-button is clicked.
EDIT: Try resetting it inside of your completion listener. Scratch the setter then. Try using this:
Thread.sleep(1000);
currentPosition++;
Instead of this:
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
That is in your run() function. Then it will increment from 0 to total and you won't have to worry about getting or setting the currentposition, just the progress which is being done with the previous change below.
mp.setOnCompletionListener(new OnCompletionListener() {
//When audio is done will change pause to play
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
//Reset here
progressBar.setProgress(0);
}
});

Android MediaPlayer Seekbar not changing only tracking

I've got it set up with a random sound playing onCreate and I have to add a seekbar to track the audio, it moves with track but will not go back if seekbar is pulled back to another part in the audio. Any help would be great, only beginner, sorry for being a noob :).
public class player1 extends Activity implements Runnable {
private MediaPlayer mp;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private SeekBar songProgressBar;
private ImageButton playicon;
private ImageButton pauseicon;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private SeekBar seek;
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_1);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound01; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound02; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound03;
// Listeners
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player1.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start();
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.pauseicon)
if(mp.isPlaying()){
mp.pause();
ImageButton pauseicon =(ImageButton) findViewById(R.id.pauseicon);
pauseicon.setImageResource(R.drawable.playicon);
} else {
mp.start();
ImageButton pauseicon =(ImageButton) findViewById(R.id.pauseicon);
pauseicon.setImageResource(R.drawable.pauseicon);
}}});
}
public void run() {
int currentPosition= 0;
int total = mp.getDuration();
while (mp!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
songProgressBar.setProgress(currentPosition);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser) mp.seekTo(progress);
}
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivityForResult(myIntent, 0);
return true;
}
}
The run() method is never called. Instead create a Handler object in the main thread (you did already but it is unused), remove the Thread.sleep() from the run method but add a call to postDelayed() method of the Handler at the end of run() (and maybe a condition to call it only while playing).
After starting playback, call run() method once (from main thread). It will then take care about calling itself subsequently with postDelayed().

Play and Stop in One button

i'm newbie, i'm tried to make play audio play and stop for 1 button only, but i'm in trouble now.
if i touch a button when audio is playing, it doesn't stop, even playing audio again and make a double sound.
here's my code
public class ProjectisengActivity extends Activity{
ImageButton mainkan;
MediaPlayer mp;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test2);
mainkan=(ImageButton)findViewById(R.id.imageButton1);
mainkan.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
go();
}
});
public void go(){
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
}
else {
mp.start();
}
i'm create for android 3.0 (HoneyComb)
try below code in go function....
public void go() {
if(mp == null) {
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
}
if(mp.isPlaying()){
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.seekTo(0);
}
else {
mp.start();
}
}
It is simple, you should follow these steps to achieve this.
In your test2.xml create two buttons name start and stop.
Set the android:visibility attribute gone of stop button in xml file.
Now in your activity get the id of these two buttons and write the code for
starting and stopping of media player.
Set the visibility attribute gone on start click and visible of stop button,
follow its opposite on stop click.
I think you have wrong this line :
mp=MediaPlayer.create(ProjectisengActivity.this, R.raw.test);
You create new instance every time user clicks the button, so it's never playing and starts again. Put this line into onCreate rather than go()
Try also this,
public class MainActivity extends Activity {
MediaPlayer mPlayer;
int flag = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButton = (Button) findViewById(R.id.button1);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (flag == 0) {
Log.v("Inside if", "Success" + "");
mPlayer = MediaPlayer.create(getApplicationContext(),
R.raw.sample);
mPlayer.start();
flag++;
} else {
Log.v("Inside else", "Success" + "");
mPlayer.stop();
mPlayer.release();
flag = 0;
}
}
});
}
}

Categories

Resources